Lesson · Comprehensions & Expressive Iteration
Generator Expressions
55 min readGenerator Expressions
Generator expressions use comprehension syntax but produce values lazily. They reduce peak memory for streaming pipelines, while introducing one-pass consumption and deferred execution behavior.
Learning goals
- Describe the difference between
(expr for ...)and[expr for ...]in what gets built and when. - Trace the state of a generator through successive
next()calls and explain why it advances instead of restarting. - Explain why
sum(n * n for n in range(10))never materializes a full list of squares. - Predict what happens when a generator is consumed twice, and name the fix.
- Decide when laziness is worth its constraints (no
len, no indexing, no second pass).
Mental model
A generator expression builds an object, not a collection: each request computes one item and then the generator pauses, so peak memory stays at the current item plus the generator's own state. The same object cannot be replayed; a second pass needs a fresh generator expression, or a list if the data must be revisited.
A recipe and a position, not a collection
one item per request, then a pause
Mental model
the same mechanism as a compact list
generator expression (expr for item in iterable) ↓ next(gen) or a for loop asks for a value compute one item, hand it over the generator pauses where it stopped ↓ the consumer wants a second pass start a new generator the old one is exhausted
Core idea
(n * n for n in range(1_000_000)) creates a generator object that computes each square only when a consumer asks for it, so no million-element list is ever built. That laziness lowers peak memory and lets a pipeline stop early, and it costs three abilities: no len(), no indexing, and no second pass over the same object. The choice between a generator expression and a list comprehension is the choice between streaming the data once and holding all of it.
Lazy evaluation
Lazy evaluation postpones work until a consumer requests a value. It can reduce memory and avoid unnecessary work, while also delaying side effects and exceptions.
Memory behavior
A generator expression stores iteration state instead of materializing all output elements. This reduces peak memory, but the source and captured objects can remain referenced while iteration is incomplete.
One-pass consumption
An iterator is generally consumed as it advances. After exhaustion, reuse requires a new iterator from the original iterable or regeneration of the data.
Generator vs list comprehension
A generator expression (expr for item in iterable) creates a generator object that computes values on demand, while a list comprehension [expr for item in iterable] eagerly builds the whole list. The generator keeps peak memory low and allows early exit, but gives up len, indexing, and replay; the list costs memory up front and can be traversed as many times as needed.
Walkthrough
squares = (n * n for n in range(1_000_000))binds a generator object; constructing it runs no multiplication and allocates no result list, even though the implied output would be a million items.- The first
next(squares)advances the generator until it yields1; the second resumes exactly where the first stopped and yields4, because the generator keeps its position between calls. sum(n * n for n in range(10))is a fresh generator expression consumed to exhaustion insidesum, which adds the ten squares to285without ever building the list[0, 1, 4, ...].- Predict before running: the two numbers the
nextcalls print, and whethersum(squares)afterwards would start from the beginning.
Experiments to try
- Call
next(squares)a third time and record the value; then calllist(squares)and count what it returns, since the first three items are already spent. - Run
len(squares)andsquares[0]and read theTypeErroreach raises; a generator is not a sequence. - Build
(1 / n for n in [2, 1, 0]), assign it without consuming, then pull values until theZeroDivisionError; note that the error appears only when the zero is requested. - Loop over
squaresand break after five values, then callnext(squares)and observe that the generator resumes at the sixth item instead of restarting.
Common mistakes
- Reusing an exhausted generator:
list(squares)twice returns the full list and then[], because the object stores one position in the source, not the values it has produced. - Treating a generator like a sequence:
len(squares)andsquares[0]raiseTypeError, and wrapping it inlist()is the deliberate way to regain those abilities. - Forgetting that laziness defers side effects: a
printor anopeninside the expression runs only when that item is requested, so an unconsumed generator performs none of it and raises none of its errors. - Expecting the memory win to cover the source: the generator keeps its source and captured objects alive while it is unfinished, so the saving is the unbuilt output, not the input data.
Practice: Easy
- Write
squares = (n * n for n in range(5))and printnext(squares)three times; write the three expected values before running. - Call
list(squares)on the generator from task 1 and explain why the result does not have five items. - Build
[n * n for n in range(3)]and(n * n for n in range(3)), print both, and note which one the REPL displays with its values.
Practice: Medium
- Consume the first five values of
squareswith aforloop that breaks, then callnext(squares); state which value comes back and why. - Rewrite the
sum(n * n for n in range(10))line asgen = (n * n for n in range(10))followed by twosum(gen)calls; explain the second result. - Build
(1 / n for n in [2, 1, 0]), assign it without consuming, then step through withnextuntil theZeroDivisionError; state exactly when the error appears relative to the assignment.
Practice: Hard
- Build a two-stage pipeline for a list of words, one generator expression filtering and a second mapping, where one stage calls a helper
trace(x)that printsxand returns it; predict when each print happens, then verify. - Compare
sys.getsizeof([n for n in range(100_000)])withsys.getsizeof((n for n in range(100_000)))and explain why the second size does not grow with the range. - Write a function that sums the first
neven squares from any iterable of numbers; decide where it must materialize a list versus where it can stay lazy, then test it with a list and with an already exhausted generator.
Lesson checklist
- I can tell what is built when a generator expression is created versus when it is consumed.
- I can trace a generator through
nextcalls and say where it resumes. - I can explain the memory difference between
(expr for ...)and[expr for ...]. - I can predict what breaks when a generator is reused or treated as a sequence.
Remember
A generator expression builds a lazy object: `next` and `for` pull one computed value at a time, and the generator pauses in between, which keeps peak memory near a single item. The trade is that the pass is one-way: no `len`, no indexing, and no replay without a fresh generator. Use it for streaming pipelines, and use a list comprehension when the data must be held or revisited.
Interview angles
What is the main purpose of **Lazy evaluation**?+
Lazy evaluation postpones work until a consumer requests a value. It can reduce memory and avoid unnecessary work, while also delaying side effects and exceptions.
What should you pay attention to when using **Memory behavior**?+
A generator expression stores iteration state instead of materializing all output elements. This reduces peak memory, but the source and captured objects can remain referenced while iteration is incomplete.
How does **One-pass consumption** fit into this lesson?+
An iterator is generally consumed as it advances. After exhaustion, reuse requires a new iterator from the original iterable or regeneration of the data.
Why does `list(squares)` return `[]` when it is called a second time on the same generator?+
A generator stores one position in its source, not the values it has produced. After the first pass it is exhausted, so any further consumption yields nothing until a fresh generator expression is created.