Sub topic 7
Generator expressions
A generator expression builds a lazy iterator from a one-line loop. It looks like a list comprehension, but it produces values one at a time instead of building a whole list. This chapter assumes you know list comprehensions, the iterator protocol (__iter__, __next__, StopIteration), and how a generator function pauses at yield.
Syntax and meaning
A generator expression uses the comprehension syntax with parentheses instead of square brackets:
squares = (x * x for x in range(5))
print(type(squares)) # <class 'generator'>
print(next(squares)) # 0
print(next(squares)) # 1
print(list(squares)) # [4, 9, 16]The object is an ordinary generator. It has __iter__ and __next__, and it is its own iterator. The expression does no work when you create it. Each next() call computes one more value. The list(squares) call at the end collects only what is left, because the first two values were already consumed.
A generator expression is shorthand for a generator function:
def squares_gen(iterable):
for x in iterable:
yield x * x
squares = squares_gen(range(5))Use the expression form when the logic fits on one line, and the function form when you need statements, several yield points, or try/finally.
The parts of the expression
The general shape is the same as a list comprehension:
(output_expression for target in iterable if condition)You can add more for clauses and if clauses. They nest from left to right, like nested loops:
pairs = (x * y for x in range(3) for y in range(3) if x < y)
print(list(pairs)) # [0, 0, 2]This yields 0*1, 0*2 and 1*2. An if placed after the iterable filters items out. A conditional expression placed in the output part transforms every item instead:
nums = range(6)
evens_only = (n for n in nums if n % 2 == 0)
zeroed = (n if n % 2 == 0 else 0 for n in nums)
print(list(evens_only)) # [0, 2, 4]
print(list(zeroed)) # [0, 0, 2, 0, 4, 0]The first form produces fewer items. The second always produces one output per input.
Parentheses rules
When a generator expression is the only argument of a call, the call's own parentheses are enough:
total = sum(x * x for x in range(10))
print(total) # 285If the call has other arguments, the generator expression needs its own parentheses:
print(sorted((len(w) for w in ["pear", "fig", "banana"]), reverse=True))
# [6, 4, 3]Writing sorted(len(w) for w in words, reverse=True) is a SyntaxError.
Comparison with other comprehensions
| Form | Brackets | Result | Evaluation | Reusable |
|---|---|---|---|---|
| List comprehension | `[...]` | `list` | Eager, all at once | Yes |
| Set comprehension | `{x for ...}` | `set` | Eager | Yes |
| Dict comprehension | `{k: v for ...}` | `dict` | Eager | Yes |
| Generator expression | `(...)` | `generator` | Lazy, on demand | No, single pass |
There is no tuple comprehension. (x for x in ...) is always a generator. To get a tuple, write tuple(x for x in ...).
Lazy consumption
Consumers such as sum, max, min, any, all, "".join and list pull values from the generator. The generator does work only when asked.
At no point do all the squares exist in memory together. This is why sum(x * x for x in range(10**7)) uses a tiny, constant amount of memory, while sum([x * x for x in range(10**7)]) first builds a list of ten million integers.
Short-circuiting
Because values are produced on demand, a consumer that stops early also stops the generator early:
print(any(n > 100 for n in range(10**12))) # True, after checking 101 numbersThe equivalent list comprehension would try to build a trillion-element list before any saw its first value.
The same idea works for "first match" searches. next() accepts a default for when nothing matches:
names = ["ada", "bob", "bea", "cy"]
first_b = next((n for n in names if n.startswith("b")), None)
none_c = next((n for n in names if n.startswith("z")), None)
print(first_b) # bob
print(none_c) # NoneWithout the default, next() would raise StopIteration when no item matches.
When names are evaluated
This is the most common source of surprise. A generator expression evaluates its parts at different times:
- The outermost iterable (the one after the first
for) is evaluated immediately, when the expression is created. Python callsiter()on it right then. - Everything else (the condition, the output expression, any inner
forclauses) is evaluated lazily, each time a value is requested.
Two consequences follow.
First, errors in the outermost iterable appear at creation time:
try:
g = (x for x in 5) # an int is not iterable
except TypeError as exc:
print("raised at creation:", exc)Errors in the body appear later, when you consume:
g = (1 / x for x in [1, 0])
print(next(g)) # 1.0
try:
next(g)
except ZeroDivisionError:
print("raised on the second next()")Second, other names are looked up at the moment they are used, not when the generator is created:
n = 2
g = (x * n for x in range(3))
n = 10
print(list(g)) # [0, 10, 20]The loop variable x comes from range(3), which was captured at creation. The name n is read on each step, so it sees the value 10.
The iterator for the outer source is captured, but the object behind it is not copied. If you mutate the same list before consuming, the generator sees the change:
data = [1, 2, 3]
g = (x for x in data)
data.append(4)
print(list(g)) # [1, 2, 3, 4]If you rebind data = [9] instead of mutating it, the generator still reads the original list.
Pitfalls
Single use
A generator expression can be traversed once. After it is exhausted, further passes yield nothing, and no error is raised:
words = (w.strip() for w in ["a ", " b"])
print(list(words)) # ['a', 'b']
print(list(words)) # []
print(len(list(words))) # 0A silent empty result is worse than an exception. Typical accidents include calling max(g) and then min(g) on the same generator, or checking if x in g and then looping over g. The in test consumes items up to the match. If you need several passes, build a list or tuple, or create a fresh generator each time.
No length, no indexing
Generators have no len() and do not support g[0] or slicing. Use itertools.islice to take a slice, or convert to a list if the data is small enough.
Debugging is harder
Printing a generator shows only <generator object ...>. To inspect values, wrap a copy in list() while developing, but remember that this consumes the original.
Cleverness over clarity
A long generator expression with three for clauses and two conditions is hard to read. Switch to a generator function with a named loop. The speed is about the same, and a function lets you add comments and intermediate variables.
Choosing between a list and a generator
- Use a generator expression when you consume the values once, such as feeding
sum,max,joinor aforloop. It also suits large or unbounded sources, and cases where you may stop early. - Use a list comprehension when you need
len(), indexing, repeated iteration, or the whole result at once. A list is also usually faster for small inputs, because it avoids the overhead of resuming a generator for every item.
Laziness saves memory, not necessarily time. For a short input that you will read several times, the list is simpler and often quicker.
Exercises
Exercise
What does this code print, and why? n = 3 g = (i * n for i in range(3)) n = 5 print(list(g)) print(list(g))
Show answer
It prints [0, 5, 10] and then []. The outermost iterable range(3) is captured at creation, but n is looked up each time a value is produced, so it uses 5. The first list() call exhausts the generator, so the second call gets nothing.
Exercise
Write a single expression that returns the first word in words that is longer than five characters, or "none" if there is no such word. Use words = ["tree", "garden", "sun"].
Show answer
next((w for w in words if len(w) > 5), "none") returns "garden". The default argument "none" is returned when the generator is empty, which avoids a StopIteration.
Exercise
Why does sorted(len(w) for w in words, reverse=True) fail, and how do you fix it?
Show answer
A generator expression may drop its own parentheses only when it is the sole argument of a call. Here there is a second argument, so Python raises a SyntaxError. Add parentheses: sorted((len(w) for w in words), reverse=True).