11.2. Generators#
In Iterators you wrote iterator classes by hand: __init__() to set up a position, __iter__() to return self, and __next__() to update the position and raise StopIteration at the end. A generator gives you the same kind of iterator with far less code. You write an ordinary function that uses yield to hand out each value, and Python builds the iterator, remembers the position, and raises StopIteration when the function finishes.
Like the built-in lazy iterators, generators produce values one at a time, only when asked, so they can handle large files, data streams, and sequences with no end without building a whole collection in memory. This section covers generator functions, generator expressions (the lazy counterpart of list comprehensions), and how functions such as sum(), any(), all(), and next() consume them. The next section, Pipelines and itertools, chains generators together into data pipelines.
11.2.1. Generator Functions#
A generator function looks like a regular function but contains yield. yield is the keyword that makes a function a generator. yield works like a return that pauses instead of ending: it hands a value back to whoever called next(), freezes the function at that line with its local variables intact, and continues from there on the next next().
def my_gen():
yield 1 # pauses here on first next()
yield 2 # pauses here on second next()
yield 3 # pauses here on third next()
# function returns → StopIteration is raised automatically
How yield compares with return:
|
|
|
|---|---|---|
Gives back a value |
Once |
Once per |
Afterward the function |
Ends, and its local variables are gone |
Pauses, and its local variables are kept |
Calling the function |
Runs the body |
Returns a generator object; the body runs on |
Values are therefore produced lazily, only when requested.
If yield appears anywhere in the body, even in a branch that never runs, calling the function no longer executes the body: the call returns a generator object. A generator can also contain return, which simply ends it; Python then raises StopIteration. To hand out every value from another iterable, use yield from, covered in Pipelines and itertools.
def count_up_to(max_count):
"""Yields integers 1, 2, ..., max_count."""
n = 1
while n <= max_count:
yield n
n += 1
# Calling the function returns a generator object; nothing executes yet
gen = count_up_to(5)
print(type(gen)) # <class 'generator'>
# Values are produced one at a time
print(next(gen)) # 1
print(next(gen)) # 2
# for loops consume the remaining values
for val in gen:
print(val, end=' ') # 3 4 5
print()
# A fresh generator starts from the beginning
print(list(count_up_to(5))) # [1, 2, 3, 4, 5]
<class 'generator'>
1
2
3 4 5
[1, 2, 3, 4, 5]
11.2.1.1. Watching a Generator Pause#
The comments above describe the pausing, but you can watch it happen. The generator below prints a message each time its body runs, so the output shows exactly when the code inside the function executes:
def noisy_gen():
print(" body starts")
yield 1
print(" resumed after yield 1")
yield 2
print(" resumed after yield 2, reaching the end")
gen = noisy_gen()
print("generator created") # nothing from the body has printed yet
print("next ->", next(gen)) # runs the body up to the first yield
print("next ->", next(gen)) # resumes right after yield 1
try:
next(gen) # resumes, runs to the end, raises StopIteration
except StopIteration:
print("StopIteration: the body finished")
generator created
body starts
next -> 1
resumed after yield 1
next -> 2
resumed after yield 2, reaching the end
StopIteration: the body finished
Read the output in order. Creating the generator printed nothing, so the body had not started. Each next() ran only as far as the next yield, and each call resumed exactly where the last one paused. When the body ran off its end, Python raised StopIteration for you, which is the same signal a custom iterator’s __next__() raises by hand.
### Exercise: Even Numbers Generator
# 1. Write a generator function `evens_up_to(limit)` that yields the even
# numbers 0, 2, 4, ... up to and including `limit`.
# 2. Create a generator with evens_up_to(10) and print its first two values
# with next().
# 3. Print list() of the same generator to see the values that are left.
# Print exactly:
# 0
# 2
# [4, 6, 8, 10]
### Your code starts here.
### Your code ends here.
0
2
[4, 6, 8, 10]
11.2.1.2. From Iterator Classes to Generators#
In Iterators you wrote Countdown as a class with __init__(), __iter__(), and __next__(), and you saved the position in self.current by hand. A generator function does the same job in a few lines, because Python saves the local variables and the position for you at each yield:
# The class version from Iterators
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
# The generator version: same behavior, no protocol methods to write
def countdown(start):
current = start
while current > 0:
yield current
current -= 1
print(list(Countdown(5))) # [5, 4, 3, 2, 1]
print(list(countdown(5))) # [5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
Every generator is an iterator, but not every iterator is a generator. Iterator names the protocol: any object whose __iter__() returns itself and whose __next__() hands out the next value. A generator is one convenient way to get such an object without writing the class:
gen = countdown(3)
print(iter(gen) is gen) # True: __iter__() returns the generator itself
print(next(gen)) # 3: __next__() hands out the next value
True
3
The two ways of making an iterator differ mainly in who does the bookkeeping:
Iterator class |
Generator |
||
|---|---|---|---|
1 |
How you create it |
A class with |
A function containing |
2 |
Where the position is kept |
In attributes you manage, such as |
Automatically, in the paused function’s local variables |
3 |
How it ends |
|
The function body finishes, and Python raises |
4 |
Access from outside |
Other code can read its attributes or call methods you add, such as a |
Its state is hidden inside the paused function |
5 |
Typical use |
Iterators that need attributes or methods other code uses |
Pipelines, streams, lazy sequences, and most everyday cases |
Both kinds of iterator are single-use: once a Countdown object or a countdown() generator reaches the end, it stays there. A class becomes reusable when its __iter__() returns a new iterator each time instead of self. The simplest way to do that is to write __iter__() as a generator function. Each time the object is iterated, whether by a for loop, list(), or anything else, Python calls iter(), which calls __iter__(), which starts a fresh generator:
class CountdownRange:
"""A reusable iterable: every loop starts again from `start`."""
def __init__(self, start):
self.start = start
def __iter__(self): # a generator method: yield makes it one
current = self.start
while current > 0:
yield current
current -= 1
timer = CountdownRange(3)
for n in timer:
print(n) # 3, 2, 1
for n in timer:
print(n) # 3, 2, 1 again: a fresh generator each time
print(list(timer)) # [3, 2, 1]
print(list(timer)) # [3, 2, 1]: a fresh generator each time, like a list
3
2
1
3
2
1
[3, 2, 1]
[3, 2, 1]
This is how a list behaves: the list is an iterable that stores the data, and each iter() call produces a separate iterator that tracks one pass. CountdownRange works the same way: the class holds the data, and the generator does the stepping.
Default to a generator: it is shorter and harder to get wrong. Write a full __iter__()/__next__() class only when the iterator needs an interface beyond next(), such as a reset() method or a remaining attribute that other code reads.
11.2.2. Generator Expressions#
A generator expression has the same syntax as a list comprehension, but uses () instead of []. The result is a generator, not a list; values are computed on demand.
# List comprehension: builds the entire list in memory immediately
squares_list = [x ** 2 for x in range(1_000_000)] # about 40 MB in total
# Generator expression: produces values one at a time
squares_gen = (x ** 2 for x in range(1_000_000)) # about 200 bytes
# Python does not have tuple comprehension. Parentheses around a for clause always produce a generator expression.
The list’s total has two parts. sys.getsizeof(squares_list) reports only the list’s own array of references, about 8 MB; the one million integer objects it points to take about 32 MB more. The generator stores none of the values, only its current state.
Prefer a generator expression when you only need the values once, especially when the data is large.
import sys
# Compare memory: list vs generator
n = 1_000_000
squares_list = [x ** 2 for x in range(n)]
squares_gen = (x ** 2 for x in range(n))
print(f"List size: {sys.getsizeof(squares_list):,} bytes")
print(f"Generator size: {sys.getsizeof(squares_gen):,} bytes")
# Generator expressions compose well with sum(), max(), any(), etc.
total = sum(x ** 2 for x in range(1001)) # no intermediate list
first_mult7 = next(x for x in range(1, 100) if x % 7 == 0) # 7
print(f"Sum of squares 0-1000: {total}")
print(f"First multiple of 7: {first_mult7}")
List size: 8,448,728 bytes
Generator size: 200 bytes
Sum of squares 0-1000: 333833500
First multiple of 7: 7
11.2.2.1. Working with Generator Expressions#
A generator is not a list, so a few list habits do not carry over:
No
len()and no indexing. A generator does not know how many values it will produce, solen(gen)andgen[0]raiseTypeError. To count the items, add1for each one:sum(1 for x in items if condition).next()can take a default.next(gen)raisesStopIterationwhen nothing is left.next(gen, default)returnsdefaultinstead, which is the safe way to ask for “the first match, if any”.Parentheses. You can drop the generator’s own parentheses only when it is the only argument, as in
sum(x for x in nums). With another argument, keep them:sorted((x for x in nums), reverse=True).
nums = [4, -1, 7, 0, 3, -2, 8]
# Counting: sum one 1 per matching item (len() does not work on a generator)
negatives = sum(1 for n in nums if n < 0)
print("Negatives:", negatives) # 2
try:
len(n for n in nums)
except TypeError as e:
print("TypeError:", e)
# next() with a default: no StopIteration when nothing matches
print(next((n for n in nums if n > 5), None)) # default to None. 7
print(next((n for n in nums if n > 100), None)) # default to None
# A second argument means the generator needs its own parentheses
print(sorted((n for n in nums if n > 0), reverse=True)) # [8, 7, 4, 3]
Negatives: 2
TypeError: object of type 'generator' has no len()
7
None
[8, 7, 4, 3]
### Exercise: Running Total Generator
# 1. Write a generator function `running_total(numbers)` that yields the
# cumulative sum after each element.
# Example: running_total([1, 4, 2, 8]) yields 1, 5, 7, 15.
# 2. Write a generator expression `even_squares_gen` that yields the squares
# of even numbers from 0 to 19 (i.e., 0, 4, 16, 36, 64, 100, ..., 324).
# 3. Print list() of each.
# Print exactly:
# [1, 5, 7, 15]
# [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
### Your code starts here.
### Your code ends here.
[1, 5, 7, 15]
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
11.2.2.2. any() and all() with Generator Expressions#
In Lists you used any() and all() with list comprehensions. Now that you know generator expressions, you can drop the brackets:
# list comprehension: builds the full list, then checks
any([x > 0 for x in values])
# generator expression: stops as soon as the result is known
any(x > 0 for x in values)
The generator version is more efficient for two reasons: it never builds an intermediate list, and it lets the short-circuit save real work. any() stops at the first truthy value and all() at the first falsy one, with either a list or a generator. But with a list comprehension, every test has already run before any() starts. With a generator expression, the remaining tests are never computed.
data = [4, -1, 7, 0, 3, -2, 8]
# any() stops the moment it finds a True value; the rest is never checked
print(any(x < 0 for x in data)) # True (stops at -1)
# all() stops the moment it finds a False value
print(all(x > 0 for x in data)) # False (stops at -1)
# Common data-validation patterns
scores = [82, 91, 74, 88, 65]
print(all(s >= 60 for s in scores)) # True: all passed
print(any(s >= 90 for s in scores)) # True: at least one A
True
False
True
True
### Exercise: any() and all() with Generator Expressions
# 1. Use any() with a generator expression to check if any sale exceeds 2000.
# 2. Use all() with a generator expression to check if all sales are above 400.
# 3. Use next() with a generator expression to find the first sale above 1000.
# 4. Use next() with a default of None to look for a sale above 5000.
# Print exactly:
# True
# True
# 1200
# None
sales = [1200, 850, 2100, 430, 975, 1600]
### Your code starts here.
### Your code ends here.
True
True
1200
None
11.2.3. Exercises#
This task combines a generator function, generator expressions, sum(), all(), and next() with a default.
### Exercise: Order Totals
# 1. Write a generator function `order_totals(orders)` that yields
# qty * price for each (item, qty, price) tuple, skipping any order
# whose qty is 0 or less.
# 2. Use sum() to print the grand total of all order totals.
# 3. Use sum() with a generator expression to count the orders whose
# total is at least 20.
# 4. Use all() with a generator expression to check that every order
# total is under 100.
# 5. Use next() with a generator expression and a default of None to
# find the first order total above 30.
# Call order_totals(orders) again for each step: a generator is used up
# after one pass.
# Print exactly:
# Grand total: 77.0
# Orders of 20 or more: 2
# All under 100: True
# First above 30: 35.0
orders = [("pen", 4, 1.5), ("mug", 2, 12.0), ("book", 0, 20.0),
("lamp", 1, 35.0), ("ink", 3, 4.0)]
### Your code starts here.
### Your code ends here.
Grand total: 77.0
Orders of 20 or more: 2
All under 100: True
First above 30: 35.0