Sub topic 9
Generator expressions: the lazy alternative
A list comprehension builds the whole list in memory before your code can use any of it. A generator expression produces the same items one at a time, only when something asks for them. This chapter covers how that works and where it surprises people. It also covers when to pick it over a list.
This chapter assumes you can write list comprehensions with for and if clauses. It also assumes you know what an iterable is, meaning anything a for loop can walk over, such as a list, a string, a range, or an open file.
Syntax: a comprehension in parentheses
A generator expression looks like a list comprehension with parentheses instead of square brackets.
squares_list = [n * n for n in range(5)]
squares_gen = (n * n for n in range(5))
print(squares_list) # [0, 1, 4, 9, 16]
print(squares_gen) # <generator object <genexpr> at 0x...>
print(next(squares_gen)) # 0
print(next(squares_gen)) # 1
print(list(squares_gen)) # [4, 9, 16]
print(list(squares_gen)) # []The square brackets produce a list. The parentheses produce a generator object, which is an iterator. An iterator hands out one item per next() call and remembers where it stopped. Printing it shows only its type and address, because no items exist yet. Squares are computed only when next() asks, or when a for loop, list(), or sum() pulls items from it.
The last two lines show that a generator is used up after one pass. Once list() has taken the remaining items, there are none left. A second list() returns an empty list and raises no error.
What "lazy" means
Lazy evaluation means the work for an item happens at the moment the item is requested. The consumer drives the loop and the generator does a small step each time.
At no point do all the squares exist together. That is why this line works without building a million-item list:
total = sum(n * n for n in range(1_000_000))
print(total) # 333332833333500000The call to sum supplies the parentheses, so you don't write a second pair. A list version, sum([n * n for n in range(1_000_000)]), gives the same answer. It first allocates a list of a million integers, which takes several megabytes. The generator version keeps a small, constant amount of state.
You can see the difference in object size. sys.getsizeof reports the size of the container object itself, not of the items inside it, but the contrast still shows.
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_gen) < sys.getsizeof(as_list)) # TrueThe generator's size does not depend on how many items it will eventually produce.
Where generator expressions fit best
Use one when the result is consumed once and you don't need the items stored. Reducing functions are the most common case: sum, min, max, any, all, and str.join.
words = ["apple", "banana", "cherry"]
print(max(len(w) for w in words)) # 6
print(max((len(w) for w in []), default=0)) # 0
print(",".join(str(n) for n in range(5))) # 0,1,2,3,4
print(all(w.islower() for w in words)) # TrueThe second line uses default=0 because max of an empty sequence otherwise raises ValueError.
Short-circuiting
any stops at the first true item and all stops at the first false item. With a generator, the items after that point are never computed.
def is_even(n):
print("checking", n)
return n % 2 == 0
print(any(is_even(n) for n in [1, 3, 4, 5, 7]))
# checking 1
# checking 3
# checking 4
# TrueItems 5 and 7 are never checked. A list comprehension inside any([...]) would call is_even on all five items first, so the early exit would save nothing.
Streaming large or unbounded sources
A file object is itself a lazy iterable of lines. A generator expression over it keeps memory flat even if the file is gigabytes long. This example uses an in-memory file so it runs anywhere:
import io
log = io.StringIO("INFO start\nERROR disk\nINFO ok\nERROR net\n")
errors = sum(1 for line in log if "ERROR" in line)
print(errors) # 2Chaining into a pipeline
Because each generator pulls from the previous one, you can chain several. Each item travels through every stage before the next item starts.
lines = [" alpha ", "", " beta", " "]
stripped = (line.strip() for line in lines)
non_empty = (s for s in stripped if s)
upper = (s.upper() for s in non_empty)
print(list(upper)) # ['ALPHA', 'BETA']No intermediate lists are built. Nothing runs until list(upper) starts pulling.
Parentheses rules
A generator expression that is the only argument of a call can share the call's parentheses, as in sum(n for n in range(3)). If the call has other arguments, the generator needs its own pair.
print(sum((n for n in range(4)), 100)) # 106Writing sum(n for n in range(4), 100) is a SyntaxError. Everywhere else, such as an assignment or a return, the parentheses are required.
Differences from lists that cause bugs
One pass only
A generator cannot be restarted. If you need to loop twice, a generator is the wrong tool, or you must recreate it.
gen = (n for n in range(3))
print(max(gen)) # 2
print(list(gen)) # []The second use gets nothing. A subtler version is calling min(gen) after max(gen), which raises ValueError because min sees an empty sequence. Neither call reports that the generator was already consumed.
No length, indexing, or slicing
A generator does not know how many items it will produce. len(gen) raises TypeError, and so does gen[0]. Convert it with list(gen) if you need those operations, accepting the memory cost.
When each part is evaluated
The outermost iterable, the one after the first for, is evaluated immediately when the generator is created. Everything else waits until items are requested. Two consequences follow.
First, errors in the outermost iterable appear at creation time:
try:
gen = (x for x in 5)
except TypeError as exc:
print("failed at creation:", exc)
# failed at creation: 'int' object is not iterableErrors in the rest of the expression appear later, when that item is reached:
gen = (10 // n for n in [5, 2, 0])
print(next(gen)) # 2
print(next(gen)) # 5
try:
next(gen)
except ZeroDivisionError:
print("failed at the third item")A generator that looks harmless can therefore fail far from the line that built it. Debugging this is harder than debugging a list comprehension, which fails on its own line.
Second, the generator captures the outermost iterable object when it is created, but other names are looked up when each item is computed.
data = [1, 2, 3]
gen = (n * 10 for n in data)
data = [7, 8, 9] # rebinding the name does not affect gen
print(list(gen)) # [10, 20, 30]
factor = 2
gen = (n * factor for n in range(3))
factor = 10 # factor is looked up late, so this change is seen
print(list(gen)) # [0, 10, 20]If you mutate the captured list instead of rebinding the name, the generator sees the change, because it holds the same list object. Appending 4 to data before consuming the first generator would add 40 to its output. The simplest defense is to consume a generator soon after creating it, and to avoid changing its inputs in between.
Choosing between the forms
| Situation | Best choice | Reason |
|---|---|---|
| You need the result stored, indexed, or reused | List comprehension | A list supports `len`, indexing, and repeated passes |
| One pass into `sum`, `min`, `max`, `any`, `all` | Generator expression | No temporary list, and `any`/`all` can stop early |
| Source is huge or unbounded | Generator expression | Memory stays constant |
| Building a string with `"".join(...)` | Either | CPython's `join` turns its argument into a list internally, so a list comprehension is often slightly faster |
| Small input, result used several times | List comprehension | The memory saving is negligible, and reuse matters more |
| Work involves side effects | Plain `for` loop | The intent is clearer and the timing is predictable |
Generator expressions are not automatically faster. For small inputs the overhead of resuming a generator for each item can make them slower than a list comprehension. The reliable benefits are lower memory use and the ability to stop early. If speed matters, measure with timeit on realistic data.
Summary
A generator expression has the syntax of a list comprehension with parentheses. It yields items on demand, uses a small constant amount of memory, and lets functions like any stop early. It can be consumed only once, has no length or indexing, and defers most errors until iteration.
Exercise
What does this code print, and why? gen = (n * 2 for n in range(4)) print(next(gen)) print(sum(gen)) print(sum(gen))
Show answer
It prints 0, then 10, then 0. The first next(gen) takes the item 0 (0 2). The first sum(gen) adds the remaining items 2, 4, and 6, giving 12. The values are 12, 22, 32, so the sum is 2 + 4 + 6 = 12, not 10. The correct output is therefore 0, 12, 0. The second sum(gen) returns 0 because the generator is exhausted, and sum of an empty sequence is 0.
Exercise
A function must return the longest word in a list of words, and it should return an empty string when the list is empty. Write it with a generator expression, and explain why the default argument is needed.
Show answer
def longest(words): return max((w for w in words), key=len, default="") Without default, max raises ValueError when given an empty sequence. With default="", the empty case returns "" instead. Note that key=len is passed to max, and the generator expression needs its own parentheses because max has other arguments. For a non-empty list such as ["apple", "banana", "kiwi"], it returns "banana".