Process Data Lazily and Bound Intermediate Storage
Core idea
An iterator produces values on demand. A generator expression can avoid materializing a large intermediate list when a consumer needs only one pass. itertools.batched (Python 3.12+) makes bounded chunks for batch consumers. Total memory depends on the source, consumer and retained state; laziness does not guarantee constant memory for every pipeline.
seen = []def squares(): for i in range(5): seen.append(i) yield i*iit = squares()print(seen)print(next(it), next(it))print(seen)Only the requested values are produced. The list here records activity for demonstration, not a bounded production design.
Expected output:
[]0 1[0, 1]Consume bounded batches
from itertools import batchedfor group in batched(range(7), 3): print(len(group), sum(group))Each tuple holds at most three items; the final group can be shorter.
Expected output:
3 33 121 6Common mistake
Do not wrap an infinite iterator in list. A consumed generator cannot be restarted; recreate it if a second pass is required. Some operators such as sorted must retain inputs.
Practice
Process a range of 10000 values with batched(..., 128). Track the maximum batch length and total sum, comparing correctness with a direct sum.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lazy data processing
Check your understanding of lazy data processing.
What is printed?
g=(x*x for x in range(3))print(next(g),list(g))What is printed?
from itertools import batchedprint(list(batched(range(5),2)))Which consumer forces full materialization?
What happens to an exhausted generator?