Skip to content
Tech Interview Prep
Technical interview guide

Comprehensions & Generators

Concise, often faster ways to build sequences, and the lazy-evaluation alternative that avoids materializing them at all.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

Scope: Python 3.14, including current generator, StopIteration, and asynchronous-generator semantics.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-4

Distinguish filtering from conditional transformation in comprehension syntax.

Answer

Filtering vs. conditional transformation in comprehensions

What I'd say first: a trailing if is a filter clause. It decides whether an element produces an output at all, so the result can be shorter than the input. An if/else in the output slot is a conditional expression: every input produces exactly one output, only the value varies. The distinction is cardinality, not style: the filter changes the length contract, the conditional expression preserves it. If downstream code assumes len(result) == len(xs), only one of these two forms is safe.

The two shapes

Python
xs = [-2, -1, 0, 1, 2]

# Filter clause: 5 inputs -> 2 outputs
positives = [x for x in xs if x > 0]                 # [1, 2]

# Conditional expression in the output slot: 5 inputs -> 5 outputs
signs = ['neg' if x < 0 else 'nonneg' for x in xs]
# ['neg', 'neg', 'nonneg', 'nonneg', 'nonneg']

# Composed: filter first, transform the survivors
labels = ['big' if x > 1 else 'small' for x in xs if x > 0]
# ['small', 'big']

Worked trace of the composed form

The comprehension is [OUT for x in xs if FILTER], and the filter runs before OUT is ever evaluated. Stepping through xs = [-2, -1, 0, 1, 2]:

xx > 0 (filter)OUT evaluated?'big' if x > 1 else 'small'appended
-2Falseno——
-1Falseno——
0Falseno——
1Trueyes1 > 1 False -> 'small''small'
2Trueyes2 > 1 True -> 'big''big'

Result ['small', 'big']: five inputs, two outputs, and the conditional expression only ever saw 1 and 2. That ordering is the fact worth remembering: in [f(x) for x in xs if p(x)], p runs once per element and f runs only for survivors; in [a if p(x) else b for x in xs], p runs once per element and exactly one of a/b is evaluated (Python's conditional expression is lazy: the untaken branch is not evaluated).

Why the syntax can't be confused

A trailing if cannot take an else:

Python
[x for x in xs if x > 0 else 0]
# SyntaxError: invalid syntax

This is grammar, not an arbitrary restriction: a filter clause is a guard in the comprehension grammar, not an expression, so there is nowhere for else to attach. else only exists as part of the conditional expression A if cond else B, which must sit in the output slot before the first for. The compiler enforces the distinction for you. The same applies to the reverse mistake: [x if x > 0 for x in xs] is also a SyntaxError; the correct spelling is [x if x > 0 else 0 for x in xs]. You can stack filters ([x for x in xs if x > 0 if x < 10], ANDed), and a filter clause may follow each for in a nested comprehension.

Cost model

Both forms are O(n) time. The filter calls the predicate n times and the output expression k times, where k is the survivor count; the conditional expression calls the predicate n times and evaluates one branch n times. Memory differs: the list comprehension builds k elements versus n, so a filter that keeps 1% of a 10-million-element list allocates ~100k slots instead of 10M. As generator expressions both are lazy and O(1) extra memory. Illustrative, not benchmarked: on a 1M-element range, both forms land in the tens of milliseconds on a laptop, with the conditional expression slightly slower because it evaluates the predicate for every element and materialises a full-length list. dis.dis shows the difference structurally: the filter's conditional jump lands before the output expression, while the conditional expression's jump sits inside it.

Failure modes

  • Predicate exceptions. In the filter form, p(x) raising means that element is never transformed: the exception surfaces during iteration, before f is called. In the transform form, p(x) raising kills the whole comprehension at that element.
  • Generator laziness. g = (1/x for x in xs if x != 0) raises nothing until you iterate to the offending element, so a ZeroDivisionError can surface far from the construction site, e.g. inside sum(g) in another function.
  • Cardinality contracts. Downstream code assuming len(result) == len(xs) breaks silently with a filter. If the requirement is one output per input, use the conditional expression; if only some inputs matter, use the filter.

Rule of thumb

Ask: does every input deserve an output? Yes -> conditional expression (A if p(x) else B) in the output slot. No -> trailing if p(x) filter. Both -> filter clause first, conditional expression second, and remember the filter's predicate never sees the elements it rejected. The builtins mirror this: filter() and itertools.filterfalse() are the selection side, map() is the transform side, and the walrus lets you filter on a computed value without recomputing it. [y for x in xs if (y := f(x)) > 0] (Python 3.8+).

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-5

When should a nested comprehension become explicit loops?

Answer

When should a nested comprehension become explicit loops?

Short answer: Keep the comprehension when it maps one conceptual operation onto one output element. A transform, a filter, a flatten. Go explicit when the reader has to execute the code mentally to recover the intent: three or more for clauses, state carried across iterations, an intermediate you need to name, or a materialization boundary the caller has to know about. My ceiling is two conceptual operations.

The clause order is the loop order

A nested comprehension is sugar for nested loops, and the for clauses read outer-to-inner, left to right:

Python
flat = [f(x) for row in matrix for x in row]

flat = []
for row in matrix:
    for x in row:
        flat.append(f(x))

That equivalence is exactly why transposition bugs hide here. Two clauses swapped produce a copy instead of a transpose, and both versions look equally elegant:

Python
m = [[1, 2], [3, 4]]

a = [[m[i][j] for i in range(2)] for j in range(2)]
# j=0 -> [m[0][0], m[1][0]] = [1, 3]
# j=1 -> [m[0][1], m[1][1]] = [2, 4]
# a == [[1, 3], [2, 4]]   transpose

b = [[m[i][j] for j in range(2)] for i in range(2)]
# i=0 -> [m[0][0], m[0][1]] = [1, 2]
# i=1 -> [m[1][0], m[1][1]] = [3, 4]
# b == [[1, 2], [3, 4]]   unchanged copy

Duplicate work is the second failure mode

Each output expression is re-evaluated per inner element, so an expensive call in the expression runs once per element, not once per outer item:

Python
docs = ["a b c", "d e"]
pairs = [(x, tokenize(doc)) for doc in docs for x in tokenize(doc)]
# doc="a b c": tokenize once for the inner iterable, then once per x -> 4 calls
# doc="d e":   1 + 2 -> 3 calls
# 7 calls to tokenize for 5 tokens

pairs = []
for doc in docs:
    toks = tokenize(doc)      # 1 call per doc -> 2 total
    for x in toks:
        pairs.append((x, toks))

Seven calls versus two, and the loop version gives you toks to inspect in a debugger. An exception inside the comprehension hands you a traceback with no intermediate variable to look at.

The decision rule

SituationComprehensionExplicit loops
One transform/filter over one iterableyesoverkill
Flatten one level (for row in m for x in row)yes if trivially readableprefer when the source is nontrivial
Cartesian product of two iterablesyes—
3+ for clauses, or 2 for + conditionals + transformnoyes
Reuse an intermediate (hoisted call, partial result)no: can't name ityes
Side effects or early exitnoyes (break)

[[f(x) for x in row] for row in m] is one operation (map) applied at two levels: fine. [g(f(x)) for x in xs if p(x)] is filter + transform: fine. Once it is filter + transform + flatten + a conditional expression, name the stages:

Python
# Before
result = [normalize(t) for t in (tok for line in raw if line.strip() for tok in line.split()) if t]

# After — each line is one inspectable operation
lines = (l for l in raw if l.strip())
tokens = (t for l in lines for t in l.split())
result = [normalize(t) for t in tokens if t]

Same asymptotics, same laziness, but each stage is testable and the traceback points at a real variable.

The materialization boundary

A generator expression defers evaluation; a list comprehension materializes now. When you hand an iterable across an API boundary, the contract has to say which one it is. A generator is single-shot:

Python
def stats(xs):
    return sum(xs), max(xs)

g = (x * x for x in range(5))
stats(g)   # ValueError: max() arg is an empty sequence

sum drains the generator, so max sees nothing. The memory side is just as concrete: sum(x for x in range(10**7)) streams in O(1) extra space, while sum([x for x in range(10**7)]) builds the list first. sys.getsizeof([0] * 10**7) returns 80,000,056 bytes for the pointer array alone, and the distinct int objects add roughly 28 bytes each on 64-bit CPython: call it 360 MB before sum runs. If the function's job is to produce a collection, materialize once, explicitly, at the return.

What would change my decision

  • Measured hot path: CPython 3.12 inlined list comprehensions (PEP 709), so there is no per-element function call and the append is a single LIST_APPEND opcode instead of LOAD_METHOD append + CALL. An illustrative microbenchmark on 3.12: [x * 2 for x in range(10**6)] lands around 25 ms against roughly 40 ms for the append loop. In a profiled hot loop I'll tolerate one extra nesting level.
  • Team convention: if the codebase is comprehensions-everywhere, I still cap at two for clauses and add a comment stating the loop order.
  • Mid-incident: first move is to expand the comprehension into named loops. That alone is evidence it was past the threshold.

So the rule I apply: if I can't state what the comprehension does in one short sentence without saying "and then", it becomes explicit loops or named generator stages.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2

Translate a multi-clause comprehension into loops and explain the evaluation order.

Answer

Clarifying the question

"Multi-clause" means a comprehension with more than one for clause, plus any if clauses: [f(x, y) for x in xs if p(x) for y in g(x) if q(y)]. The claim to justify: the leftmost for is the outermost loop, and the expression desugars to nested for statements in textual order. I'll give the desugaring, trace a concrete example, and cover the failure modes that come from reading it wrong.

Core answer

Python evaluates comprehension clauses left to right, outer to inner. Each later for can reference targets bound by earlier clauses; each if filters at exactly the nesting level where it appears. The language reference's desugaring rule:

Python
[expr for T1 in I1 if cond1 for T2 in I2 if cond2]

# becomes
result = []
for T1 in I1:
    if cond1:
        for T2 in I2:
            if cond2:
                result.append(expr)

The if between the two fors sits outside the inner loop: it is checked once per T1, not once per (T1, T2) pair. That placement decides both correctness and cost, and it is the single thing interviewers probe.

Worked example

Python
rows = ["a1", "b2", "c3"]

pairs = [
    (ch, n)
    for row in rows                 # outermost
    if len(row) == 2                # filters per-row, before any inner work
    for ch, n in [(row[0], row[1])] # depends on `row`
    if n.isdigit()                  # filters per-pair
]
print(pairs)  # [('a', '1'), ('b', '2'), ('c', '3')]

Trace for row = "b2":

  1. len("b2") == 2 → pass, enter the inner clause.
  2. The inner iterable [(row[0], row[1])] is built now, with the current row binding → yields ('b', '2').
  3. '2'.isdigit() → pass, append ('b', '2').

A row like "xy" fails at step 3, after the inner iterable was already constructed. A row like "abc" fails at step 1 and never reaches the inner clause at all: that is the cost difference the clause order buys you.

Evaluation order, precisely

For [e for x in A if c1 for y in B(x) if c2]:

stepevaluatedwhencan reference
1Aonce, firstnothing
2iter(A) / next()per outer iteration—
3c1per xx
4B(x)per surviving xx
5c2per yx, y
6eper surviving yx, y

Two consequences follow directly. First, later iterables are re-evaluated per outer iteration: if B(x) is a DB query or an I/O generator, it runs once per surviving x, not once. Hoisting it out changes semantics unless it is genuinely x-independent. Second, filters guard their own level: if c1 prevents both B(x) and e; if c2 only prevents e.

Cost arithmetic

Take A of size 1,000 and B(x) of size 1,000 for every x. The comprehension runs 1,000,000 inner iterations. If c1 rejects 90% of x values, moving it to the outer level, where it already is, cuts inner work to 100,000 iterations, a 10× reduction, because B(x) is never built for rejected x. Put the same predicate at the inner level instead and you pay the full 1,000,000. That is the whole argument for clause order, and it is measurable with timeit on a two-clause comprehension over range(1000).

The classic failure: reading right-to-left

Someone skimming [y for x in xs for y in f(x)] as "for y in f(x), for x in xs" writes the equivalent of:

Python
# WRONG mental model
for y in f(x):      # NameError — x unbound
    for x in xs: ...

Or, worse, silently reorders clauses and gets a Cartesian product:

Python
[(x, y) for x in "ab" for y in "12"]
# [('a','1'), ('a','2'), ('b','1'), ('b','2')]

The cross product is not a bug in the comprehension; it is the correct semantics of two independent for clauses. The bug is the reader assuming later clauses pair element-wise. If pairing is what you want, say so with zip or itertools.product explicitly. In review, an expectation of pairing is a signal the control flow is not obvious enough.

Generator form changes timing, not order

Swap the brackets for parens and the clause order is identical, but evaluation becomes lazy:

Python
g = ((x, y) for x in range(3) if x for y in range(x))
# nothing has run yet
next(g)  # (1, 0) — first value materializes here

Each next() advances the innermost loop one step, walking back outward only when inner iterables are exhausted. So the contract for a generator expression should state: results are single-pass and not replayable; the source iterable must stay alive and unmutated during consumption; and whichever operation materializes it (list(g), sum(g), a for loop) is where exceptions and side effects surface. A generator left unconsumed leaks nothing but also does nothing: a common production surprise when someone builds a pipeline and forgets the terminal operation.

Practical guidance

  • In review, mechanically expand any comprehension with ≥2 for clauses or ≥2 if clauses into nested loops; if the expansion surprises you, rewrite the code as loops.
  • Keep the compact form when nesting is shallow (≤2 fors), iterables are cheap or obviously lazy, and filters sit at the level of the variables they reference.
  • Watch for per-iteration re-evaluation of inner iterables: the most common hidden cost, and invisible in the one-line form.
  • dis.dis shows the compiled shape: before 3.12 a comprehension compiles to its own nested code object; from 3.12 (PEP 709) it is inlined into the enclosing frame, which is why locals() and frame inspection behave differently there.

What would change the answer

  • Async comprehensions (async for, Python 3.6+) follow the same nesting rule, but each level awaits; the desugaring uses async for and the whole expression must run inside a coroutine.
  • Assignment expressions (:=, 3.8+) can bind intermediate names inside an if clause, letting you hoist an expensive computation to the filter level where it runs once per outer iteration: a legitimate fix for the re-evaluation cost without expanding to loops.
  • In Python 3.12+, comprehension inlining changed some locals() and frame-detail behavior, but the clause evaluation order described here is unchanged and documented as stable semantics.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Compare eager list comprehensions with lazy generator expressions under partial consumption.

Answer

Short answer

A list comprehension is eager: the line does not return until every element is computed and a real list object holds them. A generator expression is lazy: creating it evaluates only the outermost iterable, and each element is computed at most once, when you call next(). Under partial consumption (any(), all(), next(), itertools.islice, a first-match search) the generator does work proportional to what the consumer pulls, O(k), and holds O(1) state; the list comprehension has already paid O(n) time and O(n) memory before the consumer sees element zero. The interview follow-ups are about the three places that difference bites: error timing, the eagerly-bound source, and single-pass semantics.

Mechanics

Both forms share the clause structure expr for x in src if cond. They differ in when the clauses run.

  • List comprehension: the for/if clauses execute immediately in written nesting order, expr runs once per surviving combination, and results are appended to a list. All of it happens before the consumer runs.
  • Generator expression: the outermost iterable src is evaluated and bound now; no element work happens. Each next() advances the clause chain one step, evaluates expr, and suspends the frame.

Worked trace

Python
import sys

src = range(10_000_000)
lst = [x * x for x in src]   # 10M squares computed here
gen = (x * x for x in src)   # nothing computed

sys.getsizeof(lst)   # 80_000_056 = 8 bytes/slot * 10M + 56-byte list header
sys.getsizeof(gen)   # constant, independent of n

getsizeof(lst) counts the pointer array only; the 10M boxed ints (32 bytes each once the value exceeds 2^30) add roughly 320 MB, so the list costs ~400 MB resident. The generator object is one fixed-size frame.

Now a consumer that stops early:

Python
def first_square_ge(limit, n):
    return any(x * x >= limit for x in range(n))

first_square_ge(100, 10_000_000)

Trace: any() calls next() on the generator. x=0 → 0 >= 100 is False; x=1 → 1 >= 100 is False; … x=10 → 100 >= 100 is True, so any() returns True and the generator is suspended, then collected. 11 iterations, 11 multiplications.

The eager twin, any([x * x >= limit for x in range(n)]), builds the full 10M-element list first, then any() scans from index 0 and stops at index 10. Same answer, 10M multiplications and ~400 MB allocated. Changing [ to ( is a ~10^6 reduction in work here.

Where each wins

dimensionlist comprehensiongenerator expression
Work under partial consumptionO(n) alwaysO(k), k consumed
MemoryO(n)O(1)
Re-iterationreplayablesingle-pass; a second loop is empty
len() / indexingyesno
Exceptionsat constructionat consumption
Source readsnapshot at buildlive

Failure modes

  1. Deferred errors. [1/x for x in [0, 1]] raises ZeroDivisionError on the spot; (1/x for x in [0, 1]) builds fine and raises on the first next(). A lazy pipeline can surface a failure far from its cause.
  2. Eager source binding. (x for x in expensive()) calls expensive() immediately. Laziness covers element evaluation, not the source call.
  3. Resource cleanup. A generator holding an open file or DB cursor that is abandoned mid-iteration is closed by GC, not deterministically: wrap it or call close().
  4. No presizing. list(gen) gets no __length_hint__ from a generator, so it grows by reallocation instead of one allocation.

Measure the cost with tracemalloc peak or sys.getsizeof on the container.

Decision rule

List comprehension when the result is bounded, needed more than once, or needs len/indexing. Generator expression when the consumer may stop early (any, all, next, islice, first-match), when the source is large or unbounded, or when feeding sum, max, str.join. If a caller may replay, materialize explicitly: the single-pass contract is an API decision, not an implementation detail.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Which portions of a generator expression are eager, and which are deferred?

Answer

Short answer. Only the iterable expression of the leftmost for clause is eager. It is evaluated once, when the generator object is created, and iter() is called on the result right there. Everything else: the if filters, the element expression, the iterables of every later for clause, and the binding of the loop targets: is deferred and runs inside next(). The language reference states this directly: the leftmost for clause is evaluated immediately so its errors surface before any error in the code that consumes the generator; later for clauses cannot be, because they may depend on the previous loop's target. PEP 289 defines the same semantics by saying a genexp is equivalent to an anonymous generator function that is called immediately.

PartEvaluatedHow often
Leftmost for iterable expressionat genexp creationonce
iter() applied to itat creationonce
if conditionsinside next()each time control reaches them
Later for iterablesinside next()once per pass of the enclosing loop
Element expressioninside next()once per yielded item
Loop-target binding (x = ...)inside next()with each pull

Trace it. The element expression is evaluated last for each item, after the innermost iterable has been pulled from, and a later for iterable is re-evaluated every time the outer loop advances.

Python
# CPython 3.12
def tag(label, value):
    print(f"  {label}")
    return value

gen = (tag("element", x)
       for x in tag("iter1", [1, 2])
       if tag("if", True)
       for y in tag("iter2", [10, 20]))

print("created")
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))

Output:

  iter1
created
  if
  iter2
  element
1
  element
1
  if
  iter2
  element
2
  element
2

iter1 prints before created, so it ran at construction. iter2 prints twice, once per x, because a later for iterable is rebuilt each time control reaches it. A fifth next(gen) raises StopIteration.

Where errors land. This is the practical reason the rule matters:

Python
def boom():
    raise ValueError("boom")

g1 = (x for x in boom())          # ValueError here, at creation
g2 = (x for x in [1] if boom())   # fine at creation
next(g2)                          # ValueError here
g3 = (1 / 0 for x in [1])         # fine at creation
next(g3)                          # ZeroDivisionError here
(x for x in 5)                    # TypeError here: iter(5) fails

Mechanism. A genexp compiles to an implicit generator function; the leftmost iterable is the argument handed to it, the rest is the body. Each next() resumes the frame and runs forward until it hits a yield, so one call does one unit of work: pull an item, run the filters, run any inner loops, evaluate the element expression, yield. Nothing is buffered beyond the current item.

Failure modes.

  • Single-shot. list(g) then list(g) gives the data then []. If a consumer needs two passes, materialize or rebuild; itertools.tee buffers and can blow memory.
  • Late binding. (x * factor for x in data) reads factor at consumption time. Rebind it in between and the results differ from what the author saw at creation.
  • Shared iterator. If the leftmost iterable is an iterator already partly consumed, the genexp sees only the remainder: a common bug when a helper returns a generator over a shared source.
  • Resource lifetime. A genexp over an open file keeps the handle referenced until exhaustion or .close(). Closing raises GeneratorExit inside the frame; wrap with contextlib.closing if the consumer may abandon it.

Cost. On CPython 3.12, 64-bit, a list comprehension over 10M ints holds 10M × 8 bytes of pointers (80 MB) plus the int objects (~28 bytes each, so ~280 MB): roughly 350 MB. The generator holds one frame and one iterator reference, a few hundred bytes, independent of n. Per element a genexp is slower, since each item costs a frame resume; the gap is usually well under 2× and depends on the body, so measure rather than guess:

Python
import timeit
print(timeit.timeit("sum(x*x for x in range(1000))", number=1000))
print(timeit.timeit("sum([x*x for x in range(1000)])", number=1000))

Switch to a list comprehension when you need len(), indexing, multiple passes, or the whole result is small anyway: the per-item overhead then buys nothing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain the cost and cardinality behavior of a set comprehension.

Answer

Set comprehension: cost and cardinality behavior

The 90-second answer. A set comprehension is eager: {f(x) for x in xs} builds the entire set before the next statement runs, and it evaluates f once per input element, unconditionally. Deduplication happens after f returns, the set hashes the result and probes its table, so it saves memory, never compute. Output cardinality is the number of distinct results: at most len(xs), and at least 1 for non-empty input. If f is injective you get no collapse at all, so never size a downstream buffer assuming the set will shrink. The decision that actually changes your code is whether f is expensive relative to hashing; if it is, dedupe on a cheap key before calling f.

Cost model

Per input element you pay three things, in this order:

  1. f(x): the full cost of f, paid for every input, including inputs whose result is already in the set.
  2. hash(result): O(1) for ints (CPython hashes an int to itself, except -1, which maps to -2), O(k) for a k-byte str or a k-element tuple. CPython caches a str's hash inside the object, so re-hashing the same string object is free; a freshly built string pays siphash over all k bytes every time. Tuples never cache, so a 5-tuple costs five element hashes on every probe.
  3. Table probe: open addressing with perturb-based probing: O(1) average, O(n) worst case under adversarial collisions. On a hit, __eq__ runs, so an expensive __eq__ is part of the per-element cost too.

Total: Θ(n × cost(f)) plus Θ(n) hash-and-probe work.

The ratio that matters

Assume f is a small regex match at ~50 µs and a hash-plus-probe on a short string is ~50 ns. For 10M inputs, f costs ~500 s and the set machinery adds ~0.5 s: 0.1% of the total. The set is never the bottleneck; f is. The common bug is the opposite assumption: "the set dedupes, so the expensive work is skipped." It isn't.

Python
import time

def expensive(x):
    time.sleep(0.01)   # stand-in for a real cost (regex, parse, API call)
    return x % 3       # collapses 1_000 inputs to 3 outputs

t0 = time.perf_counter()
s = {expensive(i) for i in range(1_000)}
t1 = time.perf_counter()

print(len(s), round(t1 - t0, 2))   # 3 10.03 — full cost paid on all 1,000 inputs

(Timings illustrative; the point is that the wall clock tracks n × cost(f), not len(s) × cost(f).)

To evaluate only for unseen keys, dedupe on a cheap key first:

Python
seen, results = set(), set()
for x in xs:
    key = cheap_key(x)          # e.g. x.id, or a truncated prefix
    if key not in seen:
        seen.add(key)
        results.add(expensive(x))

Memory and eagerness

A CPython set entry is 16 bytes on 64-bit builds (a 64-bit hash plus a pointer), and the table is a power of two kept below a 3/5 fill factor, so the table alone is at least 16n / 0.6 ≈ 27n bytes, plus the object header and the distinct result objects the set keeps alive. A generator expression over the same input holds O(1) state. So {x for x in stream} over a 100M-element stream is a plausible OOM; (x for x in stream) is not, but a generator cannot dedupe, because deduplication inherently requires retained state. Uniqueness costs memory proportional to distinct outputs.

Failure modes

  • Unhashable results: {[i] for i in range(3)} raises TypeError at comprehension time, not at iteration time, because the comprehension is eager.
  • Broken __hash__/__eq__ contract: equal objects with different hashes land in different slots; you get silent cardinality inflation and wrong membership, no exception.
  • Exception inside f: propagates immediately and the partially built set is discarded; there is no partial result to inspect.
  • Hash flooding: PYTHONHASHSEED randomizes str, bytes and datetime hashes, but not int or a user-defined __hash__, so attacker-controlled ints can still drive probes toward O(n).

Ordering and alternatives

Sets are unordered; sort at the boundary (sorted(s)) if a consumer needs determinism. For order-preserving dedup, list(dict.fromkeys(xs)) keeps first-seen order with the same hash-based cost model. frozenset is hashable, so it can itself be an element of a set: useful when deduping groups rather than scalars.

Worked trace

{x % 3 for x in [0, 1, 2, 3, 4, 5]}:

xf(x)probeset after
00miss{0}
11miss{0, 1}
22miss{0, 1, 2}
30hit{0, 1, 2}
41hit{0, 1, 2}
52hit{0, 1, 2}

Six inputs, six evaluations of f, three outputs. Cardinality collapsed; cost did not.

Summary: eager evaluation; output cardinality equals distinct results (≤ inputs, possibly equal); per-element cost always paid in full; memory proportional to distinct outputs; failures surface at definition time. The one question that changes the design is whether f is expensive relative to hashing, if so, dedupe on a cheap key first.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How would you detect duplicate keys rather than silently overwrite them in a dict comprehension?

Answer

Clarifying the question

A dict comprehension is last-write-wins: pairs are evaluated left to right, and a repeated key overwrites the earlier value while the key keeps its first insertion slot. There is no hook to intercept that write, the comprehension calls dict.__setitem__ for you, so detection means making the collision observable yourself. I'll assume the source is an iterable of (key, value) pairs and that "detect" means raise on the first duplicate; I'll cover the softer contracts (collect all duplicates, keep first) below, because which one is right depends on whether uniqueness is an invariant of the output or duplicates are legal input.

Core answer: make the write path explicit

The standard move is to drop the comprehension and write the loop, so the membership check happens before the assignment:

Python
def build_unique(pairs):
    """Build a dict from (key, value) pairs, raising on duplicate keys."""
    result = {}
    for k, v in pairs:
        if k in result:                      # average O(1) hash lookup
            raise ValueError(f"duplicate key: {k!r}")
        result[k] = v
    return result

records = [("a", 1), ("b", 2), ("a", 3)]
build_unique(records)
# ValueError: duplicate key: 'a'

k in result is an average O(1) hash lookup, not a scan, so this is O(n) time and O(n) space for the result: the same asymptotics as the comprehension, plus one extra hash per pair. The worst case is O(n) per lookup under adversarial hash collisions; CPython has randomized str hashes since 3.3 (PYTHONHASHSEED), which is what keeps that from being reachable from untrusted input.

If you want to keep the comprehension shape, pre-scan with a set, then build:

Python
pairs = [("a", 1), ("b", 2), ("a", 3)]

seen = set()
dupes = [k for k, _ in pairs if k in seen or seen.add(k)]
# seen.add(k) returns None (falsy), so the condition is True only
# when k was already in seen.
if dupes:
    raise ValueError(f"duplicate keys: {sorted(set(dupes))}")

d = {k: v for k, v in pairs}   # now safe: no collisions remain

The seen.add(k) idiom is compact but clever; an explicit if k in seen: raise ...; seen.add(k) loop reads better in production. Both passes are O(n), but the source must be replayable: a one-shot generator has to be materialized first (pairs = list(gen)), which costs the whole input in memory. The single-pass build_unique avoids that and stops at the first bad key.

Worked trace

For pairs = [("a", 1), ("b", 2), ("a", 3)], the two-pass scan runs:

stepkeyk in seen?seen afternote
1"a"no{"a"}first occurrence recorded
2"b"no{"a", "b"}
3"a"yes{"a", "b"}duplicate detected, raise

Compare the silent comprehension {k: v for k, v in pairs}, which returns {"a": 3, "b": 2}: the value 1 is gone with no error, and "a" still sits in slot 0 because overwriting preserves the first insertion position. That is the hazard: the corruption is invisible, so downstream code consumes incomplete data believing it is whole.

Cost comparison

approachtime (avg)extra spacestops early?replayable source?
single-pass loopO(n)O(n) resultyes, first dupno
two-pass set scanO(n)O(n) result + O(u) seennoyes
plain comprehensionO(n)O(n) resultnever detectsno

u is the number of distinct keys. For 10M pairs the two-pass version does 20M hash operations against 10M for the single-pass loop, and the seen set holds up to 10M keys. Back-of-envelope on 64-bit CPython: a set slot is 16 bytes and the table resizes to stay under roughly two-thirds full, so 10M distinct keys land in a 2^24 = 16.7M-slot table, about 268 MB before counting the key objects themselves. That is the figure that decides the two-pass approach out for large streams.

Variants and tradeoffs

  • Keep first, log the rest: for expected noise such as layered config or idempotent event replays: d = {}; for k, v in pairs: d.setdefault(k, v). Silent, but intentional and documented.
  • Keep last: the comprehension's own semantics; correct when the contract is "latest wins", e.g. replaying an event stream.
  • Group instead of dedupe, when one key legitimately maps to many values: d = collections.defaultdict(list); for k, v in pairs: d[k].append(v). This changes the value type, so it is a contract decision, not a tactic. itertools.groupby also works but requires the input sorted by key first.
  • Report all duplicates, not just the first: collect dupes as above and raise once with the full list; better for batch ingestion where one round-trip per bad key is painful.

Failure modes and what changes the decision

  • Unhashable keys (a list or dict as key) raise TypeError at the first k in result or seen.add(k): same as the comprehension, but it surfaces during detection rather than mid-build.
  • Equal-but-not-identical keys collide by hash and equality: hash(1) == hash(True) == hash(1.0) == 1, and 0.0 == -0.0, so {1: 'a', True: 'b'} is a one-entry dict. If that is wrong for your domain, normalize keys before the check.
  • NaN keys are the reverse trap: float('nan') != float('nan'), and dict lookup falls back to identity, so {float('nan'): 1, float('nan'): 2} has length 2 in CPython. Your duplicate check will not catch it.
  • Huge sources: the two-pass approach doubles iteration and holds everything in memory. For a 10M-row stream, prefer the single-pass build_unique over a generator, raising on first collision.

The decision rule: if uniqueness is an invariant of the output, enforce it at build time and fail loudly (build_unique). If duplicates are legal input, group them. A plain dict comprehension validates nothing and destroys the evidence you would need to debug the collision.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Explain modern comprehension scope and the remaining closure hazards.

Answer

Clarifying the question

Two different things get called "comprehension scope": which names the comprehension binds and where they live, and which names it reads from the enclosing scope. The first is settled: Python 3 gives every comprehension its own function scope. The second is where the bugs still are, because reading follows ordinary closure rules. I'll answer both, and flag the walrus operator, the one deliberate exception to "nothing leaks".

Core answer

A list, set or dict comprehension and a generator expression all compile to an implicitly nested function. The loop target is a local of that function, so it cannot leak:

Python
>>> x = "outer"
>>> [x for x in range(3)]
[0, 1, 2]
>>> x
'outer'

You can see the nested scope in the code object. Inside a function, any name the comprehension reads from the enclosing function becomes a cell variable:

Python
def make(nums):
    scale = 2
    return [n * scale for n in nums]

>>> make.__code__.co_cellvars
('scale',)

dis.dis(make) shows the enclosing code doing LOAD_CONST <code object <listcomp>>, MAKE_FUNCTION, GET_ITER, CALL; the <listcomp> code object lists scale in co_freevars and loads it with LOAD_DEREF. That is the whole mechanism: the comprehension is a function, scale is a free variable, and the cell is shared with the enclosing frame.

Two consequences follow:

  1. The outermost iterable is evaluated eagerly, in the enclosing scope. [f(n) for n in get()] calls get() before the comprehension body runs, and so does (f(n) for n in get()). Only the genexp body is lazy.
  2. Names read but not bound resolve at execution time through LEGB. That is where the hazards live.

Hazards

1. Late binding of closures created inside the comprehension

Python
fns = [lambda: i for i in range(3)]
[f() for f in fns]        # [2, 2, 2]

i is one local cell, rebound each iteration; every lambda captures the cell, not the value. Fixes: lambda i=i: i (default arg binds eagerly) or a factory (lambda j: lambda: j)(i). Not comprehension-specific, a plain for loop does the same, but comprehensions invite it.

2. Walrus bindings leak out, on purpose

PEP 572 makes := inside a comprehension bind in the containing scope:

Python
total = 0
partial = [total := total + v for v in [1, 2, 3]]
# partial == [1, 3, 6]; total == 6

The canonical filter form puts the walrus in the condition and reads it in the element:

Python
data = [y for x in items if (y := f(x)) is not None]

Two restrictions: the target cannot be the comprehension's iteration variable ([x := i for i in range(3)] is a SyntaxError), and the name must already exist if you read it before the first assignment. Flag walrus-in-comprehension in review unless the leak is the point.

3. Generator expressions retain their closure

A genexp's frame lives as long as the generator, so everything it closed over stays reachable:

Python
def leak(rows):
    big = load_blob()                 # 500 MB
    return (transform(r, big) for r in rows)

If the consumer abandons the generator, big survives until the generator is collected. The generator's frame, visible via gc.get_referents(gen), holds it; gen.close() drops it immediately. Materialize what you need, or pass copies.

4. Class bodies are invisible to nested scopes

Python
class C:
    n = 3
    rows = [n * i for i in range(3)]    # NameError: name 'n' is not defined

Class scope is not part of LEGB for nested functions, so the comprehension cannot see n. Use C.n or hoist the constant to module level.

Worked trace

Python
total = 0
counts = [total := total + n for n in [1, 2, 3]]
# n=1: total=1, append 1
# n=2: total=3, append 3
# n=3: total=6, append 6
# counts == [1, 3, 6]; total == 6

squares = [n * n for n in range(3)]
# squares == [0, 1, 4]; n is not defined afterwards

Cost

A list comp builds the whole result: sys.getsizeof([0] * 1_000_000) is 8,000,056 bytes, 8 MB of pointers alone, and list(range(1_000_000)) adds roughly 28 MB of int objects (28 bytes each on 64-bit CPython), so about 36 MB. The equivalent genexp object is a few hundred bytes regardless of n. The trade: a genexp can be consumed once. Passing one to a consumer that iterates twice silently yields nothing on the second pass; itertools.tee or list() fixes it, at the cost of the memory you were saving. Illustratively, on CPython 3.12/x86-64, sum(x*x for x in range(10**7)) ran ~0.75 s against ~0.55 s for the list-comp form: the gap is the per-item generator resume.

constructloop targetwalrus targetouter names
list/set/dict compcomp-localenclosing scopeLEGB, at execution
generator expressiongenexp-localenclosing scopeLEGB, lazily per item
inside class bodycomp-localclass bodyclass attrs not visible

Tradeoffs

  • Comprehension vs loop: if the body binds several outer names or has side effects, write the loop. Comprehensions build collections.
  • Genexp vs list comp: O(1) vs O(n) memory, single-use vs re-iterable. The contract should say who materializes.
  • Version: the no-leak rule is Python 3. Code that relies on x surviving a comprehension is Python 2 folklore: delete it.

Summary: comprehension targets are private; everything a comprehension reads follows ordinary closure rules, so late binding, walrus leakage, genexp retention and class-body invisibility are the hazards that still bite.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Describe the iterable and iterator protocols and their exhaustion contract.

Answer

The 60-second answer. An iterable implements __iter__ and returns a fresh iterator. An iterator implements __next__ and __iter__ returning self. That asymmetry is the whole contract: every iterator is iterable, but a container is iterable without being an iterator, so each for loop over it gets its own cursor. Exhaustion is signalled by raising StopIteration, and once raised the iterator must keep raising it: it is spent, not reset.

How iter() resolves. iter(x) calls type(x).__iter__(x). If that is missing, CPython falls back to the legacy sequence protocol: it wraps __getitem__ in a seqiterator that calls x[0], x[1], … and stops on IndexError. So a class with only __getitem__ still loops. Gotcha: collections.abc.Iterable's __subclasshook__ checks only __iter__, so isinstance(x, Iterable) is False for a __getitem__-only class even though for works on it.

The loop desugars to:

Python
_it = iter(obj)
while True:
    try:
        x = next(_it)
    except StopIteration:
        break
    # body

StopIteration never escapes to your code: the loop swallows it. return in a generator and falling off the end both raise StopIteration at the next() boundary.

Worked trace: sticky exhaustion.

Python
it = iter([10, 20, 30])
callreturnscursor
next(it)101
next(it)202
next(it)303
next(it)StopIteration3
next(it)StopIteration3

list(it) after that is []. iter(it) is it: the same object, so a second pass sees nothing. iter([10, 20, 30]) mints a new cursor each call, so list(lst) twice gives the same list both times. Cost: next() on a list iterator is O(1); list(iterator) is O(n) time and O(n) memory, and preallocates using __length_hint__ (list iterators report their remaining count; generators do not, so list(gen) grows by reallocation).

Worked trace: the shared-iterator trap.

Python
g = (x for x in range(3))
pairs = list(zip(g, g))   # [(0, 1)]

zip pulls from its arguments in order: next(g)→0, next(g)→1, yields (0, 1); then next(g)→2, next(g)→StopIteration, so zip stops. Both slots share one cursor, so you get one pair, not three. Passing the same generator twice is almost always a bug.

Failure modes.

  • Returning a sentinel instead of raising. None is a legal element, so a consumer cannot tell "end" from "data": you get an infinite loop. Only StopIteration is sanctioned.
  • Leaking StopIteration out of a generator body. PEP 479 (default since 3.7) converts it to RuntimeError, because a bare next() inside a generator would otherwise be mistaken for the generator finishing.
  • Assuming replay. sum(xs) then len(list(xs)) gives 0 for a generator. Materialize once (xs = list(xs)) or document single-pass.
  • zip truncates to the shortest input silently; Python 3.10 added zip(..., strict=True) to raise ValueError instead.

Rule of thumb. Containers: repeatable iterables, fresh cursor per iter(). Cursors: honest single-pass iterators that raise StopIteration and keep raising it. If a caller needs replay, they materialize explicitly, which makes the O(n) cost visible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

What exactly is suspended at a `yield` expression?

Answer

Direct answer. At a yield, what is suspended is the generator's frame: the instruction pointer (CPython exposes it as gi_frame.f_lasti), the local variables (f_locals), the value stack holding the half-evaluated expression, and the block stack that tracks enclosing try/finally and loops. The frame is detached from the C stack and kept alive on the heap inside the generator object. Control returns to whoever called next(), send(), or throw(). Nothing is torn down: the generator object, its frame, and every resource the frame references stay alive until the generator is exhausted, closed, or collected.

Mechanism. Calling a generator function runs no body code; it builds a generator object in state GEN_CREATED (inspect.getgeneratorstate). The body starts on the first next(). At yield expr, expr is evaluated and handed to the caller, and the frame suspends at the YIELD_VALUE instruction. On resumption the same frame continues, and the yield expression itself evaluates to what came in: None from next(), the argument from send(x), or it raises the exception from throw(E). gi_running is True only while the frame is executing; gi_yieldfrom names the sub-iterator when suspended inside yield from (PEP 380). send(x) on a fresh generator raises TypeError: can't send non-None value to a just-started generator: prime with next() or send(None) first.

Python
import inspect

def counter():
    total = 0
    while True:
        got = yield total
        total += got if got is not None else 1

g = counter()
print(inspect.getgeneratorstate(g))   # GEN_CREATED
print(next(g))                        # 0
print(inspect.getgeneratorstate(g))   # GEN_SUSPENDED
print(g.gi_frame.f_lasti)             # int: bytecode offset of the suspended YIELD_VALUE
print(g.send(5))                      # 5
print(g.send(10))                     # 15
g.close()
print(inspect.getgeneratorstate(g))   # GEN_CLOSED
print(g.gi_frame)                     # None
callcaller seesframe state after
counter()generator objectGEN_CREATED, body not started
next(g)0total=0, suspended at yield total
g.send(5)5got=5, total=5, suspended again
g.send(10)15got=10, total=15
g.close()NoneGeneratorExit raised at the yield, frame released, GEN_CLOSED

f_lasti is a real bytecode offset, but it shifts between CPython versions: never hardcode it.

Failure modes. close() raises GeneratorExit at the yield site, so finally blocks run:

Python
def guarded():
    try:
        yield "ready"
    finally:
        print("cleanup ran")

g = guarded()
print(next(g))   # ready
g.close()        # prints: cleanup ran

If the generator yields again while handling GeneratorExit, CPython raises RuntimeError: generator ignored GeneratorExit:

Python
def bad():
    try:
        yield 1
    finally:
        yield 2

g = bad(); next(g)
g.close()   # RuntimeError: generator ignored GeneratorExit

A suspended frame holds whatever it references: an open file, socket, or lock stays held across the yield until the generator is exhausted or closed. A half-consumed generator that is garbage-collected runs its finally blocks via close(). And a suspended generator is a one-shot cursor, not a collection: it cannot be replayed, so a consumer that needs two passes must materialize (list(gen)) or rebuild it.

Trade-offs. The suspended frame is O(locals), a few hundred bytes, which is why sum(x*x for x in range(10**8)) runs in constant memory while the list version materializes 10⁸ pointers (8 B each = 0.8 GB) plus 10⁸ int objects (28 B each ≈ 2.8 GB), roughly 3.6 GB. The cost is per-item resumption: each next() is a C-level frame switch, more expensive than advancing a list iterator, so measure before assuming laziness is free. If you need random access, replay, or len(), use a list; if you need bidirectional suspend/resume, send-value semantics are the tool: the machinery async def (PEP 525) built on.

Version note. The frame-on-heap, resumable-frame model is CPython's implementation. The language spec (PEP 255, PEP 342) guarantees the observable semantics (suspension, send/None, exception injection) not the memory layout.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Explain generator return values and their relationship to `yield from`.

Answer

Clarifying the question

A generator has two channels. The yield stream is what a consumer sees through for or next(). The return value never enters that stream; it rides out on the StopIteration exception that ends iteration, on its .value attribute. yield from is the only construct in the language that reads it. So the real question is: how does a value leave a generator without being yielded, and who is allowed to see it?

Core mechanics

return expr inside a generator body does not return to whoever called next(). It raises StopIteration(expr), and expr lands on StopIteration.value. A bare return, or falling off the end, gives None.

Python
def inner():
    yield 1
    yield 2
    return "SUMMARY"

g = inner()
next(g)   # 1
next(g)   # 2
try:
    next(g)
except StopIteration as e:
    print(e.value)   # SUMMARY

A for loop calls next() until StopIteration, then stops: it never inspects .value. list(), sum(), comprehensions and itertools consumers behave the same way. That split is deliberate: PEP 380 separated "stream data" from "termination metadata" so ordinary loops stay simple and never have to decide whether a final value is a value or an item.

yield from captures the return value

result = yield from sub does three things at once: it re-yields every value sub produces, forwards send(), throw() and close() into sub, and evaluates to sub's return value once sub terminates.

Python
def outer():
    result = yield from inner()
    yield f"got: {result}"

list(outer())   # [1, 2, 'got: SUMMARY']

Timing matters: result is bound only after the sub-generator is exhausted. And if outer is itself consumed by a for loop, outer's own return value is discarded in turn. The value surfaces only where someone catches StopIteration or delegates with yield from.

Worked trace

stepcodeeffect
1next(g)inner runs to yield 1, returns 1
2next(g)resumes, runs to yield 2, returns 2
3next(g)resumes, hits return "SUMMARY", raises StopIteration("SUMMARY"), .value == "SUMMARY"
4for x in inner()loop ends on StopIteration; .value dropped
5r = yield from inner()re-yields 1, 2; catches StopIteration; r == "SUMMARY"

The classic mistake

Expecting the return value to show up as a final yielded item:

Python
def bad():
    yield from inner()

list(bad())   # [1, 2] — "SUMMARY" is gone

If a caller needs the summary as data, yield it explicitly:

Python
def explicit():
    yield from inner()
    yield "SUMMARY"

list(explicit())   # [1, 2, 'SUMMARY']

Named APIs and version history

  • StopIteration.value: PEP 342 (Python 2.5) gave StopIteration a value and added send(), throw() and close() to the generator protocol.
  • yield from: PEP 380, shipped in Python 3.3.
  • PEP 479 (Python 3.7): a StopIteration that propagates out of a generator body is converted to RuntimeError. You cannot set a return value with raise StopIteration("x"); you must return x. A stray next() inside a generator no longer silently terminates it either.
  • yield from on a plain iterable: yield from [1, 2] evaluates to None, because a list has no return value.
  • close() throws GeneratorExit into the generator; if the generator yields in response, CPython raises RuntimeError: generator ignored GeneratorExit.
  • inspect.getgeneratorstate() reports GEN_CREATED, GEN_RUNNING, GEN_SUSPENDED or GEN_CLOSED: the states a delegating chain moves through.
  • collections.abc.Generator is the ABC carrying send, throw, close and __next__.
  • Pre-3.5 coroutines were written with @asyncio.coroutine and yield from; PEP 492 replaced that with async def / await in Python 3.5, where await is essentially yield from restricted to awaitables.

When to use each

  • Return value + yield from: delegation protocols where the return value is a result, not an item. Recursive tree walks that aggregate upward, parser combinators, and the pre-async coroutine style.
  • Explicit yield: anything a for loop should see. Default for data pipelines.

Costs and failure modes:

  • Each yield from level keeps a suspended frame alive, so a chain of N delegators holds N frames. Forwarding one value is O(1), but the chain is O(N) in memory and every hop adds a frame to tracebacks. CPython's default recursion limit is 1000, so very deep chains can hit RecursionError.
  • Return values are invisible to for/list() consumers: good for not polluting streams, bad if the caller doesn't know the protocol.
  • throw() into the delegator is delivered into the sub-generator; if the sub-generator doesn't handle it, the delegator sees it too. Failures surface at the delegation boundary, not at the top.
  • Generators are one-shot: once exhausted, the return value is gone. Materialize it if you need it twice.

What would change the decision

If the consumer chain is heterogeneous (some callers use for, some need the summary) prefer explicit yields, or wrap the generator in a plain function that returns a small result object. Reserve return-value plumbing for chains written by the same author with a documented protocol: "sub-generators return their aggregate; the top-level driver catches StopIteration.value or uses yield from."

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Why did PEP 479 change accidental `StopIteration` in generators?

Answer

The 90-second answer. StopIteration is overloaded. It is an ordinary exception and the iterator protocol's "I'm exhausted" signal, and the interpreter reads that signal at the generator's frame boundary. If a generator body calls next() on some other iterator and that call raises StopIteration, the exception travels up through the generator's own frame, where the interpreter cannot distinguish it from the generator finishing normally. The generator ends early, the consumer sees a short sequence, and nothing is raised. PEP 479 (implemented in 3.5 behind from __future__ import generator_stop, the default from 3.7) replaces any StopIteration about to escape a generator frame with RuntimeError, so the bug becomes loud and points at the line that caused it.

Mechanism. A for loop, next(it), list(it) and yield from all treat StopIteration as "done", but only at the boundary of the iterator they are driving. A generator's frame is such a boundary. So the interpreter's exhaustion check and the generator's own code share one exception type, and the check wins. The fix is to make the two cases distinguishable by type: an escaping StopIteration is rewritten to RuntimeError with the original exception attached as __cause__, while a StopIteration caught inside the generator body is untouched.

A worked trace.

Python
def pairs(rows):
    it = iter(rows)
    while True:
        try:
            a = next(it)
        except StopIteration:
            return          # deliberate end: caught locally
        b = next(it)        # uncaught: raises StopIteration on odd-length input
        yield (a, b)

Step through list(pairs([1, 2, 3, 4])): a = 1, b = 2, yield (1, 2); a = 3, b = 4, yield (3, 4); a = next(it) raises StopIteration, caught, return. Result: [(1, 2), (3, 4)].

Now list(pairs([1, 2, 3])): a = 1, b = 2, yield (1, 2); a = 3; b = next(it) raises StopIteration with nothing to catch it. Pre-PEP 479 that exception escapes the generator frame, the interpreter reads it as exhaustion, and the call returns [(1, 2)]: the 3 is gone and no error is raised. Under PEP 479 the same escape becomes:

RuntimeError: generator raised StopIteration

with the StopIteration from b = next(it) as __cause__, so the traceback names the generator frame and the offending line instead of leaving you to notice a missing element three layers up.

SituationPre-3.7 defaultPEP 479
Uncaught next(it) raises StopIteration in a generatorgenerator ends silently, output truncatedRuntimeError: generator raised StopIteration
try/except StopIteration around the callcaught, generator continuesunchanged
return in the generator bodyends the generatorunchanged
raise StopIteration in the generator bodyends the generator silentlyRuntimeError
StopIteration in a plain function or methodpropagatesunchanged

Why RuntimeError rather than letting it propagate. Letting it through would keep the ambiguity: every generator's completion would still be indistinguishable from a nested iterator's exhaustion. Changing the type preserves the invariant that StopIteration crossing a generator frame is a bug in that generator's code, and it makes the exception uncatchable by accident: a surrounding for or next() will not swallow it as "done".

Trade-offs and failure modes. The change broke real code: generators that used raise StopIteration as a control-flow stop, and pre-3.5 helper libraries that relied on the old behaviour. That is why it shipped as a __future__ flag first and only became the default in 3.7. The failure mode it introduces is a new one: a broad except Exception above the generator will now swallow the RuntimeError and you are back to silent truncation, just with a different exception type. Detect it by logging the exception type at the consumer boundary, or by letting it reach the top of the call stack in tests.

Migration. Grep generator bodies for raise StopIteration and replace with return. Audit bare next(it) calls inside generators: either wrap them in a local try/except StopIteration, or use next(it, sentinel) with a sentinel object that cannot appear in the data. On 3.6 and earlier you cannot rely on the conversion, so the local-catch discipline is required regardless; on 3.7+ it is the interpreter's job and your remaining task is not to hide the RuntimeError.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Compare `yield from` with manually iterating over a subgenerator.

Answer

yield from vs. manual iteration over a subgenerator

The 90-second answer. Assume CPython 3.x and a plain generator as the subgenerator. yield from sub is specified by PEP 380 and is not sugar for for x in sub: yield x. The loop forwards values; yield from forwards the protocol (send, throw, close) and evaluates to the subgenerator's return value. The two are indistinguishable to a consumer that only calls next(), which is exactly why the difference stays invisible until a coroutine pipeline or a recursive traversal breaks. Use the loop when you want to interpose on each item; use yield from when you want a transparent pipe.

What the loop actually forwards. for x in sub: yield x drives the subgenerator with next() only. Every value it produces is re-yielded by the outer frame, so the sequence is identical. But the outer frame is now the suspension point: anything the consumer sends or throws lands in the outer yield x expression, not in the subgenerator. yield from instead suspends the delegating generator inside the subgenerator, so consumer operations are routed to the subgenerator's own suspension point.

Python
def manual(sub):
    for x in sub:
        yield x

def delegated(sub):
    yield from sub

print(list(manual(i * 2 for i in range(3))))     # [0, 2, 4]
print(list(delegated(i * 2 for i in range(3))))  # [0, 2, 4]

1. The return value is captured, not dropped. yield from evaluates to StopIteration.value; a for loop swallows StopIteration and the value is gone. This is the mechanism await relies on to return a result.

Python
def sub():
    yield 1
    yield 2
    return 42

def manual():
    for x in sub():
        yield x

def delegated():
    result = yield from sub()
    yield result

print(list(manual()))    # [1, 2]      -- 42 lost
print(list(delegated())) # [1, 2, 42]  -- return value surfaced

2. send() reaches the subgenerator. With the manual loop the sent value is delivered to the outer yield x and discarded, so the subgenerator only ever sees None from the loop's next() calls.

Python
def accumulator():
    total = 0
    while True:
        value = yield total
        if value is None:
            return total
        total += value

def delegated():
    result = yield from accumulator()
    yield result

def manual():
    for x in accumulator():
        yield x

g = delegated(); next(g)   # 0
g.send(5)                  # 5
g.send(7)                  # 12
g.send(None)               # 12  -- sub's return value surfaced

g = manual(); next(g)      # 0
g.send(5)                  # StopIteration: 5 never reached accumulator(),
                           # which saw None and returned

3. throw() and close() land in different frames. throw() on a yield from chain raises the exception at the subgenerator's suspension point, where its except/finally can handle it. On the manual loop it is raised in the outer frame at yield x, and the subgenerator is left suspended.

Python
def sub():
    try:
        yield 1
        yield 2
    except ValueError:
        print('sub saw ValueError')
        yield 99

def delegated():
    yield from sub()

def manual():
    for x in sub():
        yield x

g = delegated(); next(g)
print(g.throw(ValueError))   # sub saw ValueError / 99

g = manual(); next(g)
try:
    g.throw(ValueError)
except ValueError:
    print('outer saw ValueError')   # sub never sees it

close() behaves the same way: on the delegating generator it raises GeneratorExit inside the subgenerator at its suspension point, so its finally runs at a point you control. With the manual loop the GeneratorExit is raised in the outer frame, and the subgenerator is only closed when that frame is torn down.

4. Stack depth and per-item cost. Each hop in the manual loop resumes a Python frame; yield from delegates inside CPython's generator-send loop. The structural consequence is checkable: a delegation chain deeper than sys.getrecursionlimit() (1000 by default) raises RecursionError with the manual loop and does not with yield from. The constant-factor difference per item is measurable with timeit on your target interpreter: the extra Python frame per hop is the reason it exists.

The bug this question is really about. yield sub emits the generator object as one item; yield from sub emits its elements.

Python
def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield flatten(item)          # BUG: yields the generator object
        else:
            yield item

print(list(flatten([1, [2, 3]])))
# [1, <generator object flatten at 0x...>]

def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)     # correct: delegates element-wise
        else:
            yield item

print(list(flatten([1, [2, [3, 4]]])))   # [1, 2, 3, 4]

When the manual loop is the right call. Use it when you genuinely want a valve in the pipe: transform, filter, log, or batch each item, or attach a resource boundary the subgenerator should not own. Use yield from for composition, recursive traversals, and any pipeline where send/throw/close must reach the inner generator, and it is the only way to observe the subgenerator's return value. One ownership caveat: yield from makes the two generators share a lifecycle, so close() on the outer closes the inner; if the subgenerator is owned elsewhere, delegation transfers that ownership implicitly.

Operationfor x in sub: yield xyield from sub
next() valuesforwardedforwarded
send(v) to subdiscarded in outer framerouted to sub
throw() into subraised in outer frameraised at sub's suspension point
close() cleanupsub closed when outer frame is torn downsub's finally runs at the close point
sub's return valuelostcaptured as the expression's value
Deep chainsbounded by sys.getrecursionlimit()not bounded per hop

Bottom line: the manual loop forwards data; yield from forwards the protocol. Reach for yield from unless you specifically need to interpose on each item, and never write yield sub when you mean yield from sub.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Describe a defensible bidirectional protocol built with `send`.

Answer

A defensible bidirectional protocol built with send

The 90-second answer

send resumes a generator and makes the paused yield expression evaluate to the value you pass. That one fact is the whole protocol: a generator is a coroutine with one input channel (what you send) and one output channel (what it yields back). A defensible protocol pins down four things before anyone writes a caller. First, the first activation must be next(gen) or gen.send(None): anything else raises TypeError: can't send non-None value to a just-started generator. Second, which values are data and which are control. Third, what send returns: the state before or after applying the input. Fourth, how close() and throw() propagate. Get those four right and the generator is a small, testable state machine with O(1) state and O(1) work per item. Get them wrong and you have a one-shot object whose failure mode is a TypeError three frames deep in someone else's code.

Mechanics

  • gen.send(v) resumes at the paused yield; that expression evaluates to v, and send returns the next yielded value.
  • First activation: next(gen) or gen.send(None). Both advance to the first yield.
  • gen.close() raises GeneratorExit at the pause point; a finally block runs, but yielding inside it raises RuntimeError: generator ignored GeneratorExit.
  • gen.throw(exc) injects an exception at the pause point: the consumer-to-generator error channel.
  • Sending to an exhausted generator raises StopIteration; generators are one-shot, so replay means a fresh call.

A concrete protocol: running average with a reset channel

Python
def running_average():
    """Protocol:
      - send(float)  -> current average (float)
      - send(None)   -> reset, returns 0.0
      - close()      -> allowed; no cleanup needed
    """
    total, count = 0.0, 0
    while True:
        x = yield (total / count) if count else 0.0
        if x is None:            # control channel
            total, count = 0.0, 0
        else:                    # data channel
            total += x
            count += 1

avg = running_average()
next(avg)            # prime: advance to first yield (send(None) equivalent)
avg.send(10.0)       # -> 10.0
avg.send(20.0)       # -> 15.0
avg.send(None)       # -> 0.0  (reset)
avg.send(4.0)        # -> 4.0

Trace of avg.send(20.0): the generator is paused at x = yield ... after having yielded 10.0. The yield expression evaluates to 20.0, so x = 20.0. It is not None, so total becomes 10.0 + 20.0 = 30.0 and count becomes 2. The loop re-yields 30.0 / 2 = 15.0, which is what send returns. The key insight: the value returned by send is produced after consuming the input. One synchronous round-trip per call, unlike a queue where inputs and outputs are decoupled.

Making it defensible

  1. Document the channel semantics. Which values are data vs. control (here None = reset)? What is the return value: the state before or after applying the input? Pick one and test it.
  2. Prime explicitly. Wrap in a helper so callers can't hit the just-started TypeError:
Python
def coroutine(fn):
    def start(*args, **kw):
        gen = fn(*args, **kw)
        next(gen)
        return gen
    return start
  1. Define termination. close() must work: any try/finally in the generator runs, and the generator must not yield again inside finally.
  2. Define error direction. Consumer-to-generator errors go via gen.throw(ValueError(...)); generator-to-consumer errors just propagate out of send.
  3. Test the contract directly:
Python
def test_reset():
    g = running_average(); next(g)
    g.send(10.0); assert g.send(None) == 0.0
    assert g.send(4.0) == 4.0

def test_close_is_clean():
    g = running_average(); next(g)
    g.close()          # no exception

Failure modes

  • Sending to an exhausted generator raises StopIteration: the protocol must state whether the stream is replayable (generators are one-shot; a fresh call is required).
  • send on a just-started generator with a non-None value raises TypeError: hence the priming wrapper.
  • A consumer that treats send as "append an input to the output stream" mis-models it: send is a synchronous round-trip, not a buffer. If you need decoupled producer/consumer flow, that's a queue, not send.
  • Debugging is harder: the stack switches between caller and generator, so exceptions carry mixed frames.

Trade-offs and when to change the decision

send is the right tool when there is genuine per-item feedback: running statistics, tokenizers feeding tokens back (the PEP 342 coroutine style), or yield-based trampolines. It is the wrong tool for general application flow: since PEP 380, yield from plus async def/asyncio.Queue expresses the same coroutine structure with clearer ownership, await points, and cancellation semantics. My rule: use send only when the bidirectional protocol is small, documented, and directly tested; the moment you need multiple consumers, replay, or backpressure, move to an ordinary iterator (pull-only) or an async queue (decoupled).

approachinput channeloutput channelbackpressurecancellationper-item cost
send coroutinegen.send(v)yield returnnone (synchronous round-trip)close() / throw()O(1)
pull-only iteratornonenext(it)natural (consumer pulls)drop the referenceO(1)
asyncio.Queueawait q.put(v)await q.get()bounded maxsize blocks producertask.cancel()O(1) amortized

Worked check

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How do `throw` and exception handling interact at a suspension point?

Answer

What happens at the suspension point

gen.throw(exc) is not a kill switch and it never restarts the generator. It resumes the suspended frame and raises exc at the exact expression that is suspended, the yield, as though the value being yielded had raised it. That single rule decides which handlers can see it: only the try/except/finally blocks that are live on the generator's frame stack at that yield. Locals, loop position and open handles are untouched, so the handler can log, roll back a half-written batch, and resume.

On a live generator there are exactly three outcomes, and code that drives a generator has to handle all three:

what the generator does after the raisewhat the caller sees
handler yields another valuethrow() returns that value; generator suspended again
handler returns or falls off the endthrow() raises StopIteration (.value is the generator's return value, PEP 380); generator closed
nothing on the frame stack catches itthrow() raises the injected exception in the caller; finally blocks have already run; generator closed

Worked trace, checked against CPython 3.12:

Python
def resilient():
    state = "start"
    try:
        while True:
            x = yield state            # the suspension point
            state = f"got {x}"
    except ValueError as e:
        yield f"recovered from {e}"    # throw() returns this

g = resilient()
next(g)                       # 'start' — frame suspended at the yield
g.throw(ValueError("boom"))   # 'recovered from boom' — raised at the yield, caught
next(g)                       # StopIteration — handler yielded once, then the function ended

The last line is the part people get wrong. The recovery yield leaves the frame suspended inside the except block; the next resume runs that handler to the end of the function, so StopIteration comes out and g.gi_frame becomes None. A recovering handler buys one more round trip, not an immortal generator. Delete the try and the same g.throw(...) raises ValueError in the caller, with any finally run before the generator is closed.

Timing matters where the raise lands: the code up to the yield in that iteration has already run and the code after it has not. The handler is picked by where the yield sits in the generator's source, not by where throw() was called from: wrap the yield (or the yield from) in a try if you want to intercept it.

Two boundaries are worth pinning down. Throwing into a generator that never started (inspect.getgeneratorstate(g) == 'GEN_CREATED') or one already exhausted ('GEN_CLOSED') runs no generator code at all: CPython raises the injected exception straight back in the caller. And hand-rolled delegation is not delegation: with for x in inner: yield x the throw hits the outer yield and leaves inner suspended and unclosed, while yield from (PEP 380) forwards throw to the subgenerator and re-raises there if it declines to handle it.

GeneratorExit is the special case. g.close() throws it at the yield; a handler may do cleanup and return, but yielding again raises RuntimeError: generator ignored GeneratorExit. This is also how @contextmanager works: __exit__ calls gen.throw(exc) with the body's exception, and if the wrapped generator yields a second time instead of stopping, contextlib raises RuntimeError: generator didn't stop after throw().

Async has the same geometry. coro.throw(exc) and task.cancel() raise CancelledError at the await the task is parked on: cancellation is cooperative precisely because the throw lands at the suspension point and is fatal only if nothing handles it. Async generators get athrow() and aclose(); one that ignores GeneratorExit raises RuntimeError: async generator ignored GeneratorExit, and a dropped async generator is finalized through the loop's asyncgen hook (loop.shutdown_asyncgens() under asyncio.run), so its finally can run a loop iteration later rather than at the drop.

API note: pass a single exception instance. The three-argument form gen.throw(type, value, traceback) is deprecated since Python 3.12.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How would you provide fail-fast validation around a generator function?

Answer

Fail-fast validation around a generator function

What I'd say first. Calling a function whose body contains yield runs no code: it builds a generator object and returns it. The body starts on the first next(). So validation written inside the generator, even above the first yield, fires at the first consumption point, which can be a different stack frame, a different thread, or minutes later in a pipeline. Fail-fast means the caller learns about bad arguments at the call site. The fix is to split the function in two: a plain function that validates and returns, and an inner generator that does the yielding. The plain function's body runs at call time; only the inner one is lazy.

The split.

Python
from collections.abc import Iterable

def read_batches(sizes):
    if not isinstance(sizes, Iterable):
        raise TypeError(f"sizes must be iterable, got {type(sizes).__name__}")
    sizes = list(sizes)                      # O(n) time, O(n) memory
    if not sizes:
        raise ValueError("sizes must be non-empty")
    for i, n in enumerate(sizes):
        if not isinstance(n, int) or isinstance(n, bool) or n < 0:
            raise TypeError(f"sizes[{i}] must be a non-negative int, got {n!r}")
    return _read_batches_impl(sizes)

def _read_batches_impl(sizes):
    for n in sizes:
        yield list(range(n))

isinstance(True, int) is True, hence the explicit bool rejection. inspect.isgeneratorfunction(read_batches) is now False: worth knowing if a framework introspects the callable.

Trace.

  • read_batches(None) → isinstance fails → TypeError at the call site. No generator object exists.
  • read_batches([]) → list([]) is [] → ValueError at the call site.
  • read_batches([3, -1]) → passes the emptiness check, then i=1, n=-1 → TypeError: sizes[1] must be a non-negative int, got -1.
  • read_batches([2]) → returns a generator; next(g) → [0, 1]; next(g) → StopIteration.

Contrast with the naive version:

Python
def bad(sizes):
    if not sizes:
        raise ValueError("empty")
    yield from sizes

g = bad([])     # nothing raised; g is a generator
next(g)         # ValueError raised here, at the consumer

Contract points.

PointChoiceWhat I'd pick
Argument validationeager in wrapper vs. lazy in bodyeager
Per-item validationlazy, at yieldlazy: you can't check items you haven't read
Replayabilityone-shot vs. re-iterableone-shot; document it
Source ownershipconsume/close the input?list() consumes it; if you don't materialize, close in finally
Error timingcall site vs. first next()call site for args, documented

Costs and failure modes.

  • The wrapper is one extra Python-level call per generator creation: tens of nanoseconds on CPython 3.12, so roughly 50 ms across a million generators. Irrelevant unless you're creating them in a hot loop.
  • list(sizes) destroys laziness and costs O(n) memory. If the source must stay lazy (a 10 GB file, a socket) validate only what's checkable without consuming (isinstance(sizes, Iterable)) and accept that emptiness surfaces late. Say so in the docstring.
  • yield from over a caller-supplied iterable propagates that iterable's exceptions at consumption time; the wrapper can't pre-empt them.
  • An eagerly validated generator that's never iterated still holds its frame. Abandoned generators are collected by GC, not closed: GeneratorExit never fires. If the source holds a file or connection, wrap it with contextlib.closing or a with block.
  • @contextlib.contextmanager has the same hazard: the decorated function's body runs at __enter__, not at the call that builds the context manager. Validate before you return the manager.
  • Async generators (PEP 525) behave identically: async def with yield runs nothing until the first __anext__; inspect.isasyncgenfunction tells you which you have.

When the split isn't worth it. If the generator is consumed once, immediately, in the same statement, for x in read_batches(data):, the eager/lazy distinction barely matters. The wrapper earns its keep when the generator is stored, passed to another function, or consumed later, which is the normal case in pipelines and fixtures.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design an API that avoids accidental reuse of one-shot iterators.

Answer

The 90-second answer

Assume Python 3.12 and a library API that takes an iterable. The hazard is one line of CPython semantics: iter(gen) is gen returns True. A generator is its own iterator, so a second traversal resumes from the suspension point and yields nothing. No exception, no warning: just an empty result. The API fix is to make replayability part of the type rather than the docstring: accept Iterator[T] when you consume once and say so in the signature, accept Sequence[T] when you need two passes, and never accept a bare Iterable[T] and iterate it twice. Where you must take an arbitrary iterable, either materialize it once at a named line or wrap it so a second pass raises.

Why reuse is silent

iter([1, 2]) is [1, 2] is False: a list hands back a fresh iterator each time. iter(numbers()) is numbers() is True: a generator hands back itself, already positioned. So sum(gen) followed by list(gen) gives 6 then []. The failure surfaces far from the cause: a downstream consumer sees zero rows and reports "no data" instead of "source already drained".

Three tiers

Tier 1: signature says one-shot.

Python
from collections.abc import Iterator, Sequence

def process(items: Iterator[Row]) -> list[Row]:
    """Consumes `items` exactly once; caller must not reuse it."""
    return [transform(r) for r in items]

Tier 2: signature says replayable.

Python
def process_replayable(items: Sequence[Row]) -> list[Row]:
    validate(items)                        # pass 1
    return [transform(r) for r in items]   # pass 2 — safe, it is a Sequence

The callee materializes at a named line, so the O(n) cost is attributable.

Tier 3: accept anything, fail loudly on reuse.

Python
class OneShot:
    """Wraps an iterator; a second traversal raises instead of yielding nothing."""
    def __init__(self, it):
        self._it = iter(it)
        self._done = False

    def __iter__(self):
        if self._done:
            raise RuntimeError("one-shot iterator already consumed")
        return self

    def __next__(self):
        if self._done:
            raise RuntimeError("one-shot iterator already consumed")
        try:
            return next(self._it)
        except StopIteration:
            self._done = True
            raise

Trace

Python
def numbers():
    yield from range(3)

gen = numbers()
print(sum(gen))    # 6
print(list(gen))   # []

w = OneShot(numbers())
print(sum(w))      # 6
print(list(w))     # RuntimeError: one-shot iterator already consumed

sum(w) calls iter(w) once (returns self, _done still False), then next(w) four times: 0, 1, 2, then StopIteration, which sets _done = True and re-raises so sum returns 6. The next iter(w) hits the guard and raises.

Choosing between them

StrategyMemorySecond passUse when
list(items)8 B/pointer + objectreplaysbounded, ≲1M items
OneShot wrapperO(1)RuntimeErrorstreaming, want loud failure
itertools.tee(it, 2)O(k) bufferedboth iterators independentconsumers advance in lockstep
factory lambda: numbers()O(1)fresh iteratorregeneration is cheap

Real numbers, 64-bit CPython 3.12: sys.getsizeof(list(range(1000))) is 8056. 56-byte list header plus 8 bytes per pointer. Materializing range(10_000_000) costs 80 MB of pointers plus 28 bytes per int object (values above 256 are not cached), roughly 360 MB. tee is not a discount: if consumer A drains all n items while B has not started, tee holds all n, so you pay the same 360 MB plus two iterator objects. more_itertools.seekable behaves the same way: it buffers everything consumed to allow rewinding.

Failure modes and detection

  • Silent empty result. Detect with assert len(out) == expected at the boundary, or a counting wrapper that logs consumed=0 on entry.
  • Wrapper bypass. OneShot only catches reuse through the wrapper; a caller holding the raw generator still gets silence. Keep the raw object out of the caller's scope.
  • tee skew. Unbounded buffering when one consumer lags. Only safe with a bounded-lag guarantee.
  • Factory side effects. lambda: open(path) re-reads the file and re-runs any side effects per traversal.

Contract

State three things: replayability (does the return replay?), ownership (who drains the source?), and the materialization point (which call turns a stream into memory). For unbounded sources (log tailing, multi-GB scans) materialization is off the table; use a distinct Stream[T] type so the one-shot contract is machine-checkable rather than doc-only.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Design deterministic cleanup for a partially consumed generator.

Answer

Clarifying the question

Assume a generator owns a resource (an open file, socket, or DB cursor) and a consumer stops early: a break, an exception, or just losing interest partway. "Deterministic" means the resource is released at a known statement, not at some later GC point. I'll answer for CPython 3.11+ and flag where PyPy differs.

Core answer

Three closure paths, with different guarantees:

  1. Garbage collection. When the generator object is collected, CPython calls close() on it. Not deterministic: immediate under refcounting, deferred or never under PyPy, and skipped at interpreter shutdown.
  2. Explicit gen.close(). Deterministic, but the caller must remember, and it does not reach a generator wrapped in a plain for loop.
  3. with / contextlib.closing. Deterministic, exception-safe, and composes.

The mechanism underneath: close() raises GeneratorExit at the suspended yield. The generator must let it propagate or re-raise it, and must not yield again: otherwise you get RuntimeError: generator ignored GeneratorExit. finally blocks still run, which is exactly where cleanup belongs.

Worked example

Python
import contextlib

def lines(path):
    f = open(path)
    try:
        for line in f:
            yield line.rstrip()
    finally:
        f.close()

g = lines("big.log")
next(g)      # opens the file, reads one line, suspends at yield
g.close()    # finally runs now; f closed synchronously

Trace: next(g) opens the file, reads one line, and suspends at yield. g.close() throws GeneratorExit at that yield; the finally runs f.close(); the exception propagates out of close(), which returns None. The file descriptor is released at that statement, not later.

The failure mode the interviewer is probing for:

Python
def bad(path):
    f = open(path)
    try:
        for line in f:
            yield line.rstrip()
    except BaseException:       # catches GeneratorExit too
        yield "cleanup marker"  # RuntimeError: generator ignored GeneratorExit
    finally:
        f.close()

except BaseException (or a bare except:) swallows GeneratorExit; yielding inside the handler violates the close contract and Python raises RuntimeError. Even returning normally after swallowing it is wrong: let it propagate.

The chain problem

The hard case is source -> transform -> consumer with an early break. yield from propagates close() deterministically:

Python
def source(n):
    with open("data.txt") as f:
        for i, line in enumerate(f):
            if i >= n:
                return
            yield line

def upper(gen):
    yield from gen

c = upper(source(10))
next(c)
c.close()   # GeneratorExit -> upper -> yield from -> source.close() -> with exits -> f closed

Trace: next(c) opens data.txt and yields line 0 through upper. c.close() raises GeneratorExit at upper's yield from; yield from calls source.close(), which raises GeneratorExit at source's yield; the with block exits and closes the file; both generators finish. One close() at the top closes the whole chain.

That only holds when each link delegates with yield from. A for-loop transform breaks it:

Python
def upper(gen):
    for line in gen:
        yield line.upper()

close() here raises GeneratorExit at yield line.upper(); the frame unwinds and drops the local gen. In CPython the refcount hits zero and gen.close() runs, but that is refcounting, not the close protocol. On PyPy, or if anything else holds a reference, source stays open until GC. So delegate with yield from, not a for loop, whenever the inner generator owns a resource.

Tradeoffs

ApproachDeterministic?Composes across chains?Cost
Rely on GCNoN/Azero code; leaks under PyPy/shutdown
try/finally + explicit close()Yesonly via yield fromcaller must close
with inside generatorYesvia yield fromnone: preferred
list() materializeYesbreaks lazinessO(n) memory

Design rules

  • Put resources in with / try/finally inside the generator that owns them.
  • Never catch BaseException around a yield.
  • Delegate with yield from, not a for loop, when the inner generator holds a resource.
  • Wrap consumption: with contextlib.closing(source(10)) as gen:, or contextlib.aclosing (3.10+) for async generators.
  • A for loop with break does not close the generator; it just drops the reference.

Concrete costs: reading a 10 GB log line-by-line keeps RSS flat (O(1) memory); list(f) materializes ~10 GB and can OOM. Each leaked generator holds one file descriptor, and the default ulimit -n is often 1024, so roughly a thousand leaked generators exhaust it and open() starts raising OSError: [Errno 24] Too many open files.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Which itertools tools can retain significant state, and why?

Answer

Direct answer

Four things in itertools keep more than O(1) state: cycle, tee, the combinatorial constructors (product, permutations, combinations, combinations_with_replacement), and, since 3.12. batched. groupby is technically O(1) in bytes, but it shares one cursor between the outer iterator and the group iterators it hands out, which is the bug people actually hit. Everything else (chain, islice, takewhile, dropwhile, count, repeat, accumulate, pairwise, zip_longest, filterfalse, compress, starmap) is counters, flags, or one pending item per input.

The reason splits cleanly: laziness governs output, not input retention. A tool only grows if it must replay a stream (cycle), split it between consumers (tee), or index it (product family). When it must, it has to own a copy of whatever it cannot rewind.

ToolWhat it keepsGrowthSymptom when it bites
cyclea saved list of every item from the first passO(n)RSS climbs on a long or infinite source → OOM
teeshared item buffer between branchesO(fastest − slowest)memory tracks consumer skew; abandoned branch → whole stream
product / permutations / combinations / combinations_with_replacementa tuple copy of each input pool (+ index arrays of size r)O(Σ pool)generator input silently materialized before the first yield
batched (3.12+)current batch listO(n) for batch size nby design; big n is a big buffer
groupbycurrent key + one lookahead itemO(1)stale group iterators silently yield nothing

Mechanism, with the traps

cycle: the documented equivalent keeps saved = [] and appends every element during the first pass, then replays saved forever. The first pass therefore streams and caches: on CPython 3.12, next(cycle(count())) returns 0 immediately. The catch is that an infinite source never ends that first pass, so saved grows unboundedly and the process dies of memory long before a second pass starts.

Python
from itertools import cycle, count
it = cycle(count())
[next(it) for _ in range(5)]   # [0, 1, 2, 3, 4] — looks healthy
# then ~36 bytes/item forever: 28-byte int + 8-byte list slot
# (values <= 256 are cached singletons). 10M items ≈ 360 MB.

tee(it, n=2) (default 2 branches): both branches read one underlying iterator; CPython keeps a linked list of buffered item nodes shared by the branches, and a node is freed only once every branch has passed it. So retained memory is the gap between the fastest and slowest consumer, not the length of the stream:

Python
from itertools import tee, count
fast, slow = tee(count())
for _ in range(1_000_000):
    next(fast)
next(slow)   # 0 — ~1M items now sitting in the shared buffer

At 1M rows of ~200 bytes that is roughly a quarter of a gigabyte nobody allocated explicitly. If one branch is iterated to completion and the other abandoned, the buffer becomes the entire stream.

The combinatorial family: product(*pools) calls tuple(pool) on every argument before the first tuple is emitted, and permutations/combinations/combinations_with_replacement do the same to their one pool, then keep index arrays of size r. Lazy output, eager input: product(gen_of_10m, repeat=2) holds all 10M items before yielding anything. Note tuple(t) is t, so passing tuples avoids the copy; passing a generator does not. Output count is the other axis: product(range(100), repeat=4) is 10⁸ tuples (≈7 GB if materialized), combinations(range(1000), 5) is ≈8×10¹².

groupby: one shared cursor, and the group iterators borrow it. Save them and read later and you get nothing:

Python
from itertools import groupby
rows = [('a', 1), ('a', 2), ('b', 3)]

# wrong: keep the group iterators
kept = {k: g for k, g in groupby(rows, key=lambda r: r[0])}
{k: list(g) for k, g in kept.items()}   # {'a': [], 'b': []}

# right: drain each group while it is current
{k: [v for _, v in g] for k, g in groupby(rows, key=lambda r: r[0])}
# {'a': [1, 2], 'b': [3]}

groupby also never sorts: it groups consecutive runs, so the usual sorted(..., key=...) in front is itself an O(n) memory cost.

Choosing between them

Two passes over a one-shot iterator: use tee only when the consumers advance in lockstep. If one consumer eats most of the data before the other starts, list(src) is the documented better choice: bounded, and it doesn't pin a node per item. If the source is re-iterable (list, range, file you can reopen), just iterate twice and pay zero buffering. Similarly, cycle over a sequence you already hold builds a second pointer list for nothing; while True: for x in seq: ... does the same work with O(1) state. For grouping, groupby streams; collections.defaultdict(list) buys random access at O(n) memory.

Detection: RSS or tracemalloc snapshots that grow linearly with consumer skew point at tee; growth proportional to source length points at cycle or a materialized pool. Sizes above are CPython 3.12 on 64-bit Linux, approximate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Explain the buffering model and operational risks of `itertools.tee`.

Answer

What a strong candidate says first

itertools.tee(it, n=2) splits one iterator into n independent iterators over the same values. It does not copy and does not replay: all branches pull from the single source, and every value the source yields is appended to a per-branch buffer until every branch has consumed it. So the memory retained is proportional to the skew between the fastest and slowest branch, not the stream length. Keep the branches in lockstep and the buffer is O(1); let one race ahead and the buffer becomes effectively list(source). That single fact is the trade-off, and it is why tee is a lockstep primitive.

Mechanics

CPython implements this in C with a shared linked list of pending values, but the documented recipe captures the semantics exactly:

Python
import collections

def tee(iterable, n=2):
    it = iter(iterable)
    deques = [collections.deque() for _ in range(n)]
    def gen(my_deque):
        while True:
            if not my_deque:                 # this branch is the furthest behind
                try:
                    new = next(it)           # pull once from the shared source
                except StopIteration:
                    return
                for d in deques:             # every branch buffers a reference
                    d.append(new)
            yield my_deque.popleft()
    return tuple(gen(d) for d in deques)

Three consequences follow directly:

  1. The source is advanced exactly once per value, by whichever branch is behind. Side effects on the source (socket read, log line, DB cursor step) fire once, at the moment the slowest branch forces the pull, not when you call tee.
  2. Buffer depth equals the maximum distance between branches. If a is 1,000,000 items ahead of b, ~1,000,000 references are held.
  3. A buffered item is not freed until the slowest branch drops it.

Worked trace

a, b = tee(range(5)), then step through:

callreturnssource pulls (cum.)a bufferb buffer
--0[][]
next(a)01[][0]
next(a)12[][0, 1]
next(b)02[][1]
next(b)12[][]
next(a)23[][2]
next(b)23[][]

Six next() calls advanced the source three times. At the peak (after next(a); next(a)) branch a has consumed two values and b none, so b's buffer depth is 2, exactly the skew. next(b) never pulls while its buffer is non-empty; the source only moves again when a catches up and then outruns b.

Memory cost, with numbers

Python
import itertools, sys

a, b = itertools.tee(iter(range(10_000_000)))
list(itertools.islice(a, 10_000_000))   # drain a; b never moves
# b's buffer now holds ~10M references to distinct int objects

sys.getsizeof(1_000_000) is 28 bytes on 64-bit CPython 3.11, so ~10M int objects is ~280 MB, plus ~8 bytes per pointer in the deque's block array, another ~80 MB: roughly 360 MB retained by a call that looks like it merely splits an iterator. Changing the consumer loop to next(a); next(b) keeps the same program in the low hundreds of bytes.

When to use / avoid

SituationChoiceWhy
Two passes over a re-iterable (list, tuple, range, re-openable file)Iterate twicetee adds buffering and per-item overhead for nothing
Single-pass source, consumers roughly in lockstep, e.g. a, b = tee(it); next(b, None) for one-item lookaheadteeBuffer stays O(1)
Single-pass source, consumers drift or one is much slowerlist(it)Same worst-case memory, simpler failure mode, replayable
Adjacent pairsitertools.pairwise (3.10+)Purpose-built, no tee bookkeeping
Fan-out across threadsqueue.Queue per consumertee branches are not documented thread-safe

Failure modes worth naming

  • Silent unbounded growth under skew. No exception, no log, just RSS climbing to the OOM killer. Detect it with a producer/consumer lag metric or bound it with islice/backpressure.
  • Source side effects fire once, timed by the slowest branch. A socket read or cursor step happens seconds after the fast branch "consumed" the item.
  • Using the source after tee silently loses values. it = iter([1,2,3]); a, b = tee(it); next(it) then next(a) yields 2: the 1 was buffered nowhere. No exception, just a hole.
  • Thread races. The docs make no thread-safety guarantee. The buffer is mutated under the GIL, but a source that runs Python code (a generator) can interleave across two branches. Treat branches as single-threaded.
  • tee of a tee works but does not save memory: the innermost buffer still grows with the outermost skew, you just add indirection.

The framing I would give an interviewer: tee is a lockstep primitive whose unstated contract is "replay is free while consumers stay close." If the design cannot guarantee that, say so and materialize deliberately. An explicit list() that raises MemoryError at 10M items is far easier to reason about than a tee that OOMs only under the exact consumer-skew pattern your production traffic happens to produce.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does `groupby` differ from SQL-style global grouping?

Answer

Short answer

itertools.groupby groups consecutive runs of equal keys, not all equal keys in the stream. SQL GROUP BY partitions the entire relation by key. Hand groupby an unsorted stream and it emits the same key more than once; SQL never does. The Python equivalent of SQL GROUP BY is groupby over input sorted by the same key, or a dict/defaultdict accumulation. Mechanically, groupby is a single-pass run-length encoder with O(1) extra memory; global grouping costs either a sort (O(n log n) time) or a hash table (O(n) time, O(distinct keys) memory).

Worked trace

Three rows arrive in this order: eng/a, hr/b, eng/c. groupby(rows, key=lambda r: r["dept"]) compares each element's key to the previous element's key only. It yields eng with ['a'], then hr with ['b'], then eng again with ['c']: three groups, two of them sharing a key. SQL over the same three rows returns two rows: eng 2, hr 1.

Python
from itertools import groupby

rows = [
    {"dept": "eng", "name": "a"},
    {"dept": "hr",  "name": "b"},
    {"dept": "eng", "name": "c"},
]

for dept, grp in groupby(rows, key=lambda r: r["dept"]):
    print(dept, [r["name"] for r in grp])
# eng ['a']
# hr  ['b']
# eng ['c']

Sort by the same key and the runs merge, so the output matches SQL:

Python
rows.sort(key=lambda r: r["dept"])   # eng/a, eng/c, hr/b
for dept, grp in groupby(rows, key=lambda r: r["dept"]):
    print(dept, len(list(grp)))
# eng 2
# hr 1

Skip groupby entirely and a dict does the global grouping in one pass:

Python
from collections import defaultdict
counts = defaultdict(int)
for r in rows:
    counts[r["dept"]] += 1
# {'eng': 2, 'hr': 1}

Why it behaves this way: the shared-iterator contract

groupby returns (key, group) pairs where group is a lazy iterator over the same underlying iterator. Advancing the outer loop to the next group makes groupby consume any unconsumed elements of the previous group to find the next key: those elements are gone. Two consequences follow. First, you must consume each group before advancing; keep the group object and iterate it later and you get an empty iterator. Second, grouping can only be consecutive: a single pass with O(1) memory cannot buffer unseen future elements for an earlier key, because it never rewinds and never stores groups. Global grouping needs a sort (O(n log n), or an external sort when the data exceeds memory) or a hash table.

Python
saved = []
for k, g in groupby([1, 1, 2, 2]):
    saved.append((k, g))          # BUG: keeping the lazy group

for k, g in saved:
    print(k, list(g))
# 1 []
# 2 []

Both groups print empty: the outer loop already drained the shared source. Materialize inside the loop, saved.append((k, list(g))), or don't keep groups at all.

Tradeoffs

ApproachTimeMemoryGlobal grouping?Replayable groups?
groupby on sorted inputO(n log n) incl. sortO(1) beyond sortYes (if sorted by key)No: consume now
groupby on unsorted inputO(n)O(1)No: runs onlyNo
defaultdict accumulationO(n)O(distinct keys)YesYes
SQL GROUP BYengine-dependent (hash or sort)engine-managedYesYes

Concretely, on a 10M-row file with 1M distinct keys, the dict-of-lists path allocates 1M list objects plus 10M references: about 80 MB of pointers on 64-bit CPython 3.12 (8 bytes each) before any string data. groupby over the same file pre-sorted holds one group at a time.

  • Use groupby when input is already sorted by the key (indexed DB cursor, sorted log file), the key space is large, and you want streaming, constant-memory aggregation.
  • Use a dict when input is unsorted and the distinct-key count fits in memory. This is the honest Python equivalent of SQL GROUP BY.
  • Use SQL or pandas.DataFrame.groupby when the data already lives in a database or DataFrame: push the grouping to the engine.

Failure modes

  • Silent wrong answers, not exceptions. Unsorted input yields duplicate groups per key. If downstream code sums per group and dedupes by key keeping the last result, you lose data: plausible output, wrong totals.
  • Key-function mismatch. Sorting by key=K but grouping with a different key (or the default identity key) breaks adjacency. Sort and group must use the same key function.
  • Mixed-type keys. In Python 3, sorted raises TypeError on unorderable types such as 1 < 'a'; decide a total order, e.g. key=lambda r: (str(type(r["dept"])), r["dept"]), before sorting.
  • Stale group iterators. Any group not fully consumed before the outer loop advances is silently truncated to empty.

What changes the decision

  • Stream already sorted by the key: groupby wins. One pass, O(1) extra memory.
  • Stream unsorted and unbounded (live event feed): neither works. Global grouping over an unbounded stream is undefined without a window; use a windowed aggregation or a streaming engine such as Kafka Streams or Flink.
  • Groups must outlive the loop: materialize with list(g) per group, or use the defaultdict path from the start.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-24

How do you safely expose or consume an infinite iterator?

Answer

Safely exposing or consuming an infinite iterator

In the first two minutes: the iterator itself is harmless. itertools.count() returns instantly and holds O(1) memory. The hazard is entirely in the consumer, and the fix is to put the bound at the source boundary instead of trusting every call site. Concretely: hand out islice(stream, n) or a factory that returns a fresh generator, never a bare shared iterator; and for external streams (sockets, queues, tail -f) add a wall-clock timeout at the source, because a count bound alone cannot save you from a stream that delivers nothing and never closes.

Eager vs lazy: which operations terminate

OperationTerminates on an infinite source?Memory
list(src), sorted(src), sum(src), max(src), min(src)No: pulls until StopIterationO(n), climbs until MemoryError/OOM
islice(src, n)YesO(1)
takewhile(pred, src)Only if pred eventually goes falseO(1)
zip(src, finite)Yes, stops at the shorterO(1)
for x in src: ... breakYesO(1)
any(...) / all(...)Only if the short-circuit firesO(1)
x in srcOnly if x is reachableO(1)

any(x < 0 for x in count()) never returns; all(x < 10 for x in count()) returns False at 10; 5 in count() returns True, -1 in count() never returns.

The single-pass trap, traced

Python
from itertools import count, islice, takewhile

src = count(start=0, step=2)            # 0, 2, 4, 6, 8, 10, ...

list(islice(src, 5))                    # [0, 2, 4, 6, 8] — src now sits at 10
list(takewhile(lambda x: x < 6, src))   # [] — first pull is 10, predicate fails

The second call yields [], not [0, 2, 4], because islice already advanced the shared cursor. Fresh sources behave as expected:

Python
list(takewhile(lambda x: x < 6, count(0, 2)))   # [0, 2, 4]
list(islice(count(), 5))                        # [0, 1, 2, 3, 4]
list(islice(cycle([1, 2, 3]), 7))               # [1, 2, 3, 1, 2, 3, 1]

That is the whole argument for returning a factory (def stream(): return count()) rather than the iterator object: every caller gets an independent cursor.

What the unbounded pull actually costs

On 64-bit CPython, list(count()) allocates an 8-byte pointer per element plus a 28-byte int object for every value above 256 (small ints are cached). That is ~36 bytes per element, so 10 million elements is ~360 MB before the process dies, and it never finishes, so memory just climbs until the OOM killer or MemoryError. islice stays at O(1) regardless of n.

Bounding an external stream

Python
import time
from itertools import islice

def bounded_stream(source, limit=None, timeout=None):
    deadline = time.monotonic() + timeout if timeout else None
    for i, item in enumerate(source):
        if limit is not None and i >= limit:
            return
        if deadline is not None and time.monotonic() > deadline:
            raise TimeoutError("stream bound exceeded")
        yield item

The deadline is only checked between items. If source blocks inside next(), the generator blocks with it and the timeout never fires, so for sockets use sock.settimeout(5.0), for queues q.get(timeout=5.0), and for async generators wrap the loop in asyncio.timeout(5.0) (3.11+). A count bound and a time bound solve different failures; you usually need both.

Failure modes to name

  • Debug list() on a live stream. readings = list(sensor_stream()) in a worker hangs the thread and grows RSS until the OOM killer fires. Detect with a memory ceiling (resource.setrlimit(RLIMIT_AS, ...)) and a pytest-timeout on the suite.
  • Shared iterator across consumers. Two threads pulling the same generator interleave and each sees a random subset. Return a factory, or guard with a lock.
  • islice with a negative stop raises ValueError; islice(it, sys.maxsize) is effectively unbounded but still O(1) memory.

Tests

Python
def test_bounded_stream_terminates():
    assert len(list(bounded_stream(count(), limit=10))) == 10

def test_timeout_fires():
    with pytest.raises(TimeoutError):
        list(bounded_stream(slow_source(), timeout=0.5))

Trade-offs

islice is the cheapest bound: positional, no predicate, O(1). Use takewhile when the cutoff is a value condition. Materializing a bounded slice (list(islice(src, n))) is fine and often clearer; the sin is materializing the unbounded source. If many consumers want the same first n items, cache the bounded result instead of re-pulling a non-replayable generator. itertools.cycle over a finite input is replayable per cycle; a generator function is not: calling it again gives a new stream, not a rewind.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Audit an iterator pipeline for hidden materialization barriers.

Answer

Auditing an Iterator Pipeline for Hidden Materialization Barriers

Clarify, then assume

A hidden materialization barrier is any stage in the consumer chain that pulls the whole input, or a prefix proportional to it, into memory before yielding its first item. The producer being a generator proves nothing; the barrier is usually three stages downstream. Assume CPython 3.11+ on 64-bit, a 10 GB CSV of ~100 M key,value lines (~100 B each), and ~10 K distinct keys. The audit walks every stage from source to terminal operation and asks three questions per stage:

  1. Does it pull the whole iterator before emitting anything? sorted must see every element before the first one leaves.
  2. What state does it hold while streaming? groupby holds one group; itertools.tee holds the lag between its two branches.
  3. Where do exceptions surface? A lazy stage defers a ValueError to first consumption; a materializing stage moves it to the materialization call site.

Worked audit

Python
from itertools import groupby

def read_records(path):
    with open(path) as f:                 # file object iterates lazily
        for line in f:
            yield line.rstrip("\n")

def parse(lines):
    for line in lines:
        key, _, value = line.partition(",")
        yield key, int(value)             # int("") raises on a malformed line

records = parse(read_records("big.csv"))
ordered = sorted(records, key=lambda kv: kv[0])   # BARRIER 1
groups  = groupby(ordered, key=lambda kv: kv[0])  # streams, but only correct because of the sort
result  = {k: sum(v for _, v in grp) for k, grp in groups}  # BARRIER 2, bounded by key cardinality

Trace it on four records first, because the correctness trap is easier to see than the memory one:

Python
records = [("b", 1), ("a", 2), ("b", 3), ("a", 4)]
ordered = sorted(records, key=lambda kv: kv[0])
# [('a', 2), ('a', 4), ('b', 1), ('b', 3)]
groups = groupby(ordered, key=lambda kv: kv[0])
print({k: sum(v for _, v in g) for k, g in groups})
# {'a': 6, 'b': 4}

Drop the sorted and the same comprehension prints {'b': 3, 'a': 4}: groupby emits a new group every time the key changes, so the input splits into b:[1], a:[2], b:[3], a:[4], and the dict comprehension keeps only the last value seen per key. Silently wrong, no exception.

Now the memory trace on the 10 GB file:

stagestreams?peak retained statewhy
read_recordsyesone line, ~100 Bfile object yields per line
parseyesone tuple, ~150 Bgenerator
sorted(..., key=...)no~15 GB list + 800 MB key array + 400 MB Timsort tempmust see all n before the first yield
groupbyyesone groupcorrect only because input is sorted
dict comprehensionpartial~10 K entries, ~2 MBbounded by distinct keys, not n

Per-record arithmetic: tuple of 2 items 56 B, 8-char str key 49 + 8 = 57 B, small int 28 B, list slot 8 B ≈ 150 B. 100 M × 150 B ≈ 15 GB, plus the sort's own key array (n pointers = 800 MB) and Timsort's temp array (up to n/2 pointers = 400 MB). Peak ≈ 16 GB, so this OOMs on a 16 GB box. Verify with tracemalloc.get_traced_memory() (returns current, peak) and sys.getsizeof per object.

The fix

If the aggregation is per-key sums, sorting was never required:

Python
from collections import defaultdict

def stream_aggregate(records):
    totals = defaultdict(int)          # O(distinct keys)
    for key, value in records:         # single pass, no sorted()
        totals[key] += value
    return dict(totals)

Peak drops from ~16 GB to ~2 MB (10 K entries × ~185 B). The trade-off: you lose sorted output, and anything genuinely needing global order, top-k by value, needs heapq.nlargest(k, totals.items(), key=...), which is O(k) memory and O(m log k) time over m distinct keys, or an external merge sort if the order must be total.

Checklist

Streams (bounded state): map, filter, generator expressions, enumerate, zip, itertools.islice/takewhile/dropwhile/chain/accumulate/starmap/filterfalse, groupby on sorted input, csv.reader, file iteration, re.finditer, glob.iglob, os.walk, heapq.nlargest/nsmallest (O(k)).

Materializes: list, tuple, set, dict(pairs), sorted, list.sort, Counter, "".join, str.splitlines, f.readlines, re.findall, glob.glob, pickle.dumps, json.dumps. min/max/sum hold O(1) state but consume the iterator, ending the chain.

Two subtleties

  • itertools.tee is a barrier in disguise. It looks lazy, but it buffers every item the faster branch has consumed and the slower one has not. Memory grows with the lag, not the input, so it is invisible in a small test and fatal in production.
  • reversed() needs a sequence. On a generator it raises TypeError: argument to reversed() must be a sequence; on a list it is lazy but the list is already in memory. There is no lazy reverse of a stream.

Contract to state after the audit

  • Replayable? A generator is single-use. If any consumer needs a second pass, materialize once explicitly or re-open the source.
  • Who closes the source? If the file handle lives in the generator, the pipeline must be fully consumed or the generator closed via .close() before the handle is released.
  • Which stage materializes, and is its bound O(n), O(distinct keys), or O(k)? Name it in the review so nobody later "optimizes" the wrong stage.

Bottom line: claim bounded memory only after tracing every consumer to its terminal operation. "The first stage is a generator" is not evidence; sorted() three stages later is a disproof.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How should expected early termination influence eager-versus-lazy design?

Answer

Clarifying and answering

Early termination means the consumer stops pulling before the source is exhausted: break out of a for, next(gen) for a "find first", itertools.islice, or short-circuiting any() / all(). The design question is whether to build the pipeline eagerly (list/dict/set comprehension) or lazily (generator expression or generator function) when you expect that pattern.

Short answer: expected early termination is the strongest argument for laziness, but only when the pipeline is genuinely pull-driven and the skipped work is expensive (I/O, network, heavy compute) or the full result is large. If consumers usually drain the sequence, or the lazy form owns a resource, eager is safer.

Mechanism, with a trace

A generator expression is a paused frame. Nothing runs until the consumer calls __next__; each call advances the pipeline just far enough to yield one value. Stop pulling and the rest is never computed.

Python
from itertools import islice

calls = 0
def work(x):
    global calls
    calls += 1
    return x * x

lazy = (work(x) for x in range(1_000_000))
head = list(islice(lazy, 3))
print(head, calls)          # [0, 1, 4] 3

Trace: islice(lazy, 3) calls next(lazy) three times. Pull 1 runs work(0) → 0; pull 2 runs work(1) → 1; pull 3 runs work(2) → 4. calls is 3, and the other 999,997 calls never happen. The eager version [work(x) for x in range(1_000_000)] runs the loop to completion before the consumer sees anything, so calls is 1,000,000 and head = eager[:3] throws away 999,997 results.

Memory splits the same way. On CPython 3.12 (64-bit), sys.getsizeof(list(range(1_000_000))) is 8,000,056 bytes, a 56-byte list header plus 8 bytes per pointer, before counting the ~28 bytes per distinct int object. The generator object is a few hundred bytes regardless of n.

Where the win is, and where it isn't

Savings track expected consumption depth k, not source size n. With per-item cost c:

Consumer patternEagerLazyResult
any(pred(x) for x in rows), match at row 10 of 10M10M·c10·clazy, ~10⁶×
first k of nn·ck·clazy, n/k×
full drain (sum, list)n·cn·c + per-item __next__eager, slightly
iterate twicen·cre-run source, or emptyeager

The last row is the failure mode people miss: generators are single-shot. list(gen) twice gives the data, then []: no error, just a silently empty second pass. If the source is a file handle or DB cursor that can't be replayed, the second pass either fails or re-does the I/O.

Failure modes to name

  • Cleanup. A generator wrapping an open file or cursor that the consumer breaks out of is abandoned mid-flight. CPython's refcounting usually finalizes it promptly, but that is an implementation detail, not a language guarantee: it won't hold under PyPy or with reference cycles. Wrap the body in try/finally, or use contextlib.closing, so close() runs and GeneratorExit propagates.
  • Exception timing. A bug in the transform raises at the consumer's pull, not at construction: possibly far from the call site.
  • Side effects. Per-item logging, commits or audit writes after the break never happen. Feature or bug, depending on the contract.
  • PEP 479. Since Python 3.7, a StopIteration raised inside a generator body becomes RuntimeError, so a nested next() that runs dry won't silently end the outer generator.

Decision rule

Go lazy when expected depth is small relative to n, steps are expensive, the full result won't fit, or the source is itself a stream. Go eager when consumers almost always drain it, the result must be replayed or indexed, you want failures at construction, or the transform is cheap enough that per-item __next__ overhead dominates. When unsure, expose the lazy form and let the caller call list(): that puts the decision where consumption depth is actually known.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Choose eager or lazy evaluation for an API and defend the lifetime contract.

Answer

Clarify the boundary first

Three questions decide this before any code: does the caller iterate more than once, how large can the source get, and does the source outlive the call (file handle, DB cursor, socket)? Default assumption when the interviewer hasn't specified: a library boundary with unknown callers and potentially large sources, so the contract has to be explicit either way.

Core answer

Return a list when the caller needs repeatability, random access, a stable snapshot, or the size is known and bounded. Return a lazy iterator when the data is streamed, possibly unbounded, or the caller usually stops early. This is a lifetime contract, not a style choice: it fixes when work happens, what state stays alive, who owns the source, and where errors surface.

Two shapes

Python
import json
from typing import Iterator

def load_eager(path: str) -> list[dict]:
    with open(path) as f:                          # file closed before return
        return [json.loads(line) for line in f]    # every parse error raises here

def load_lazy(path: str) -> Iterator[dict]:
    with open(path) as f:                          # file stays open across yields
        for line in f:
            yield json.loads(line)                 # parse errors raise in the caller's loop

The second is a generator function: calling load_lazy(path) opens nothing. The with only runs on the first next().

Trace: what the lazy version actually holds

Call it = load_lazy("events.jsonl"). No descriptor is open: the body hasn't started. next(it) runs to the first yield: opens the file, reads line 1, parses it, returns the dict. The generator is now suspended inside the for loop and the with has not exited, so the descriptor stays open.

Now for ev in it: ... break after three events. The generator is suspended at the fourth yield, file still open. It closes when the generator is closed: explicitly via it.close(), or when the last reference to it is dropped and CPython refcounting finalizes it. If the caller wrote for ev in load_lazy(path): ... break with no name binding, that reference is gone at loop exit and the file closes promptly. If they kept it around, the file stays open until it is rebound or the frame exits. On PyPy, or with a reference cycle, finalization can be deferred to an arbitrary GC pass either way. Eager evaluation has no such window.

Worked arithmetic

Illustrative, stated assumptions: a 1 GB JSONL file at ~100 bytes per line, so ~10 M records; each parsed record is a dict of five short fields, ~500 bytes live in CPython.

  • Eager: peak memory ~5 GB (10 M × ~500 B) on top of the 1 GB file; time to first result is the full parse, ~20 s at ~2 µs per line.
  • Lazy, caller wants the first 50 matches at ~1 match per 200 lines: reads ~10 k lines, ~20 ms to first result, memory flat at one record.
dimensioneager listlazy generator
Peak memory~5 GB~one record
Work doneparse all 10 M linesparse until the 50th match (~10 k lines)
Time to first result~20 s~20 ms
Second passfreere-opens and re-parses, or yields nothing
Error timingat call timemid-iteration, in the caller's frame
Source lifetimeclosed before returnopen until exhausted or closed

Flip the workload, the caller needs the count and the median, and the table inverts. The generator is fully consumed anyway, so you pay a Python-level __next__ per item (~50–100 ns, ~0.5–1 s across 10 M items) and still materialize everything to compute the median. "Generators are always faster" is false; they win only when the caller stops early or needs one pass.

The contract, stated in three clauses

  1. Replayability. A list is replayable and indexable. A generator is single-use: a second for loop over an exhausted generator just ends immediately and yields nothing, while next(it) raises StopIteration. If a caller might iterate twice, return a list or make them call list(it) and own the cost.
  2. Source ownership. With laziness the producer's file, cursor or connection lives until the generator is exhausted or closed. Wrap the body in try/finally (or contextlib.closing) so an early break still releases it, and don't rely on GC timing for correctness: call it.close() explicitly when the resource is scarce.
  3. Materialization point. Name it. read_all() returns a list; iter_rows() returns an iterator. Never return a generator from a function whose name promises a finished result.

A middle ground that keeps both callers happy: return a lazy iterator and document list(result) as the supported materialization, or take a materialize: bool = False parameter so the caller picks the contract.

Failure modes and what flips the decision

  • Errors mid-stream. If the caller has already written half its output, a parse error at item 4 M is unrecoverable. Materialize first when the caller can't tolerate that; validate up front.
  • Deferred side effects. Lazy evaluation moves logging, writes and metrics to iteration time, which breaks code that assumes calling the function did the work. If the function's job is the side effect, don't be lazy.
  • Debuggability. A list is inspectable; a suspended generator shows one frame. Internal plumbing leans eager, public streaming APIs lean lazy.
  • Flip to eager: bounded size (a few MB), multiple passes, len() or slicing needed, or the source is expensive to hold open (a pooled DB connection).
  • Flip to lazy: unbounded streams, early-exit consumers (any, next(...)), pipeline stages with one item in flight, or a hard memory ceiling.

Whichever way it goes, profile with representative data before committing: the memory-versus-iterator-overhead tradeoff is workload-dependent enough that the numbers, not the idiom, should decide borderline cases.

Curated: · Written: · Reviewed:

Difficulty: Medium