Overview
Curated: · Written: · Reviewed:
Comprehensions & Generators
In one line
A list, dict or set comprehension builds its whole result at construction. A generator expression or generator function produces values on demand. Reach for a comprehension when you need the full result, replay, indexing or len(). Reach for a generator when the consumer may stop early, the input is large or unbounded, or memory must stay flat.
Key definitions
- Iterable: has
__iter__, which returns a fresh iterator on each call. - Iterator: has
__next__, raisesStopIterationwhen exhausted, and stays exhausted.iter(it) is it. - Generator expression: same grammar as a comprehension in parentheses. Only the leftmost iterable is evaluated at creation.
- Suspension point: the
yieldexpression. Locals and the instruction pointer persist between calls. send(v): resumes the suspendedyield, which evaluates tov. The first call must benext()orsend(None), or it raisesTypeError.- Materialization barrier: any step that consumes the whole stream, such as
list,sorted,setordict.
Formulas and complexity
A set comprehension runs its element expression once per input, so n calls even when only k < n distinct values survive. Deduplication saves storage, not work.
How it works
Calling a function that contains yield returns a generator object and runs none of its body. next() runs to the first yield, returns the value and suspends. send(x) resumes there with x as the value of the yield. A return v raises StopIteration with .value = v. throw(exc) raises at the suspension point. close() raises GeneratorExit there, and yielding while handling it raises RuntimeError.
A comprehension has its own implicit function scope, so its loop target does not leak. Dict comprehensions evaluate key and value for each item. A duplicate key overwrites the value but keeps the first key's position, and both calls still run.
When to use and when not to
| Need | Use |
|---|---|
replay, len(), indexing, stable snapshot | list, dict or set comprehension |
consumer stops early (any, islice, break) | generator |
| input large or unbounded | generator, with the bound placed at the source |
| one value consumed many times | materialize once |
pipeline ends in sorted() or list() | generator buys nothing: the barrier moved downstream |
| two consumers need the same stream | factory function per consumer; tee buffers the gap between them |
Generators are not automatically faster per item. Profile with real data and real consumption depth.
Traps interviewers probe
- Assuming a list comprehension is lazy. In MCQ 1,
hits = [r for r in rows if ...]filters all ten million rows beforeprintruns, so the four seconds is the full pass. Fix:next((r for r in rows if r.score > 0.9), None). - Reusing a one-shot generator. A second
forloop sees nothing because the generator is its own iterator and exhaustion is permanent. Fix: a factory function that returns a fresh generator per consumer, or a source that can be re-iterated. - Misreading scope.
[item * 2 for item in range(3)]never touches an outeritem. The walrus is the one exception and binds in the containing scope. In a class body, the outermost iterable (range(LIMIT)) is evaluated in class scope, but aLIMITused in the element or condition raisesNameError, because the comprehension's function scope skips the class body. - Raising
StopIterationinside generator logic. PEP 479 converts it toRuntimeError, on 3.7 and every later version including 3.11 and 3.14. Fix:return. In MCQ 14,list(first_n(cursor, 5))with 3 rows raisesRuntimeErroron 3.11 rather than returning 3 rows. - Yielding during cleanup. Yielding inside
except GeneratorExitraisesRuntimeError, and a lock released only after that yield is never freed. Fix: release resources infinallywith noyield.
Interview tips
Open with the contract. 'A comprehension is an eager loop folded into an expression. A generator is a paused frame that I resume one value at a time. The question is which contract I need: storage, replay, or when the work happens.'
Expected follow-ups
- Is this pipeline streaming? Trace the chain to the final consumer and name any barrier.
- What does
senddo? It sets the value of the suspendedyield. - Why did the second loop print nothing? Iterators return themselves, and exhaustion is permanent.
- How do you fail fast on bad input? The body runs at the first
next(), so atryaround the call catches nothing. Validate in a regular function that returns the generator. - A generator can be consumed once. For multi-pass aggregates over a one-shot fetch, compute all of them in one loop and keep only the rows you must return.
- What does
teecost? Its buffer grows with the distance between branches.
30-second outline
- Name the contrast: eager container versus paused frame.
- Timing: a list runs every element at construction. A generator expression defers everything except the leftmost iterable.
- Consequence: memory and early exit. Generators win when the consumer stops early or the input is large.
- One trap and its fix, such as the one-shot reuse with a factory.
- The choice for this case, with the reason.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.