Python Generators
A generator is a function that produces a sequence of values lazily — one at a time, only when asked — instead of building them all up front. Generators are the simplest way to create iterators, and they let you work with huge or even infinite data streams using very little memory.
yield instead of return
Any function that contains yield is a generator function. Calling it doesn't run the body; it returns a generator object. Each next() runs the body until the next yield, hands out that value and pauses there:
def three_steps():
print(" starting")
yield 1
print(" resumed after 1")
yield 2
print(" resumed after 2")
yield 3
print(" finishing")
gen = three_steps()
print(type(gen).__name__)
print(next(gen))
print(next(gen))
print(next(gen))
try:
next(gen)
except StopIteration:
print("done")generator
starting
1
resumed after 1
2
resumed after 2
3
finishing
done
The function's local variables survive between calls — that's what makes generators so convenient compared with writing a class with __iter__ and __next__.
Using generators in loops
Generators are iterators, so for loops, list(), sum() and friends work directly:
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(5):
print(x, end=" ")
print()
print(list(countdown(3)))
print(sum(countdown(100)))5 4 3 2 1
[3, 2, 1]
5050
Why lazy matters
A list holds every element in memory. A generator holds only its current state. Compare the sizes:
import sys
as_list = [n * n for n in range(100_000)]
as_gen = (n * n for n in range(100_000))
print(sys.getsizeof(as_list) > 100_000)
print(sys.getsizeof(as_gen) < 1_000)
print(sum(as_gen) == sum(as_list))True
True
True
Laziness also means a generator can be infinite; you just stop asking for values:
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print(list(islice(fibonacci(), 12)))
for f in fibonacci():
if f > 500:
print("first Fibonacci number above 500:", f)
break[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
first Fibonacci number above 500: 610
Building pipelines
Small generators can be chained, each one consuming the previous. Data flows through one item at a time, like an assembly line. This is a great way to process large log files:
log_lines = [
"INFO start",
"ERROR disk full",
"INFO retry",
"ERROR network down",
"WARN slow",
]
def errors(lines):
for line in lines:
if line.startswith("ERROR"):
yield line
def messages(lines):
for line in lines:
yield line.split(" ", 1)[1]
def numbered(items):
for i, item in enumerate(items, start=1):
yield f"{i}: {item}"
for row in numbered(messages(errors(log_lines))):
print(row)1: disk full
2: network down
yield from
yield from iterable yields every value from another iterable or generator — a neat way to delegate:
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5, [[6]]])))[1, 2, 3, 4, 5, 6]
Generator functions vs generator expressions
| Generator function | Generator expression | |
|---|---|---|
| Syntax | def f(): ... yield x |
(x * 2 for x in data) |
| Best for | multi-step logic, state, infinite sequences | a simple transform or filter |
| Reusable | call the function again for a new generator | write the expression again |
Note: A generator can be consumed only once. If you need the values twice, either call the generator function again or store the results in a list.
Test yourself
What does calling a generator function return?
- The first yielded value
- A list of all values
- A generator object
- None
What happens to a generator's local variables between yields?
- They are reset
- They are kept, the function is paused
- They become global
- They are deleted
What does yield from other_gen() do?
- Returns other_gen's generator object
- Yields every value produced by other_gen()
- Stops the current generator
- Converts it to a list