Generators & Iterators
Python · Intermediate
Definition
A generator is a function using yield that produces values lazily, one at a time.
Saves memory on large or infinite data streams.
Diagram
Flowchart
Example: Squares generator
def squares(n):
for i in range(n):
yield i * i
print(list(squares(4)))Output: [0, 1, 4, 9]
Complexity
O(1) memory per item
Key points
- Generator expressions use ( )
- Can only be iterated once
Interview questions
return vs yield?
return ends the function; yield pauses it and resumes on next().