Sub topic 2
Why lazy iteration saves memory
This chapter assumes you know Python loops and comprehensions, and that you have seen the iterator protocol from the previous chapter (iter() and next()). Knowing what yield does helps but is not required.
Eager versus lazy
An eager computation builds all its results at once and stores them. A lazy computation produces one result at a time, only when the consumer asks for it. A list comprehension is eager. A generator expression, which has the same syntax with parentheses, is lazy.
import sys
eager = [n * n for n in range(1_000_000)]
lazy = (n * n for n in range(1_000_000))
print(sys.getsizeof(eager))
print(sys.getsizeof(lazy))On a typical 64-bit CPython build, the list's own storage is about 8 MB. That is one pointer per element, before counting the integer objects themselves. The generator object is a couple of hundred bytes at most. Its size stays the same whether the range holds a thousand items or a trillion, because it stores only its position and its code, not the results.
What the consumer sees
Every itertools function returns a lazy iterator. Calling one does almost no work. The work happens when something pulls values out, such as a for loop, list(), sum() or next().
from itertools import count, islice
squares = (n * n for n in count(1))
first_five = islice(squares, 5)
print(sum(first_five))This prints 55. Only five squares are ever computed, even though count(1) has no end. At any moment the pipeline holds one value per stage, not the whole sequence.
Constant memory in practice
Suppose you want the total length of all lines in a large file. The eager version reads the whole file into memory first.
def total_eager(path):
lines = open(path).readlines()
return sum(len(line) for line in lines)
def total_lazy(path):
with open(path) as f:
return sum(len(line) for line in f)A file object is already a lazy iterator over its lines. total_lazy keeps one line in memory at a time, so a 50 GB file costs the same memory as a 50 KB file. The itertools functions let you keep this property while you filter, join, group and reshape the data.
Costs and limits of laziness
Lazy iteration trades memory for some restrictions.
| Property | Eager list | Lazy iterator |
|---|---|---|
| Memory | Proportional to length | Roughly constant |
| `len()` and indexing | Supported | Not supported |
| Reuse | Iterate many times | One pass only |
| Errors | Raised when built | Raised when consumed |
| Side effects | Run immediately | Run on demand |
The last two rows catch people out. If a generator stage raises an exception, you see it at the line that consumes the data, not at the line that created the pipeline. If you need to loop twice, or need random access, build a list on purpose with list().
Laziness also does not help when the answer needs all the data at once. Sorting, for example, must hold every item. Use lazy tools for streaming work such as filtering, mapping, summing and chunking, and use lists when you need the whole collection.
Key points
- Lazy iterators compute one item per request and hold only their current state.
- Memory use depends on the stage count, not on the data size.
- Every
itertoolsfunction is lazy, so nothing runs until a consumer pulls values. - The price is one-pass iteration, no
len()or indexing, and errors that surface late.
Exercise
You write squares = (n * n for n in range(5)), then run print(list(squares)) followed by print(sum(squares)). What does each line output, and why?
Show answer
The first line prints [0, 1, 4, 9, 16]. The second prints 0. The generator is consumed completely by list(), so sum() sees an empty iterator. To get both results, build a list first with squares = [n * n for n in range(5)], or create a new generator for the second call.