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.

Overview

Curated: · Written: · Reviewed:

Comprehensions & Generators

In one line

A list, dict or set comprehension builds its whole result at construction. A generator expression or generator function produces values on demand. Reach for a comprehension when you need the full result, replay, indexing or len(). Reach for a generator when the consumer may stop early, the input is large or unbounded, or memory must stay flat.

Key definitions

  • Iterable: has __iter__, which returns a fresh iterator on each call.
  • Iterator: has __next__, raises StopIteration when exhausted, and stays exhausted. iter(it) is it.
  • Generator expression: same grammar as a comprehension in parentheses. Only the leftmost iterable is evaluated at creation.
  • Suspension point: the yield expression. Locals and the instruction pointer persist between calls.
  • send(v): resumes the suspended yield, which evaluates to v. The first call must be next() or send(None), or it raises TypeError.
  • Materialization barrier: any step that consumes the whole stream, such as list, sorted, set or dict.

Formulas and complexity

O(n) time and memory for a list comprehensionO(n) \text{ time and memory for a list comprehension} O(1) to create a generator expression, then O(pipeline state) memoryO(1) \text{ to create a generator expression, then } O(\text{pipeline state}) \text{ memory}

A set comprehension runs its element expression once per input, so n calls even when only k < n distinct values survive. Deduplication saves storage, not work.

How it works

Calling a function that contains yield returns a generator object and runs none of its body. next() runs to the first yield, returns the value and suspends. send(x) resumes there with x as the value of the yield. A return v raises StopIteration with .value = v. throw(exc) raises at the suspension point. close() raises GeneratorExit there, and yielding while handling it raises RuntimeError.

next or send x return v g = gen() frame frozen, no body runs next: run to yield suspended, value out resume at yield StopIteration v

A comprehension has its own implicit function scope, so its loop target does not leak. Dict comprehensions evaluate key and value for each item. A duplicate key overwrites the value but keeps the first key's position, and both calls still run.

When to use and when not to

NeedUse
replay, len(), indexing, stable snapshotlist, dict or set comprehension
consumer stops early (any, islice, break)generator
input large or unboundedgenerator, with the bound placed at the source
one value consumed many timesmaterialize once
pipeline ends in sorted() or list()generator buys nothing: the barrier moved downstream
two consumers need the same streamfactory function per consumer; tee buffers the gap between them

Generators are not automatically faster per item. Profile with real data and real consumption depth.

Traps interviewers probe

  1. Assuming a list comprehension is lazy. In MCQ 1, hits = [r for r in rows if ...] filters all ten million rows before print runs, so the four seconds is the full pass. Fix: next((r for r in rows if r.score > 0.9), None).
  2. Reusing a one-shot generator. A second for loop sees nothing because the generator is its own iterator and exhaustion is permanent. Fix: a factory function that returns a fresh generator per consumer, or a source that can be re-iterated.
  3. Misreading scope. [item * 2 for item in range(3)] never touches an outer item. The walrus is the one exception and binds in the containing scope. In a class body, the outermost iterable (range(LIMIT)) is evaluated in class scope, but a LIMIT used in the element or condition raises NameError, because the comprehension's function scope skips the class body.
  4. Raising StopIteration inside generator logic. PEP 479 converts it to RuntimeError, on 3.7 and every later version including 3.11 and 3.14. Fix: return. In MCQ 14, list(first_n(cursor, 5)) with 3 rows raises RuntimeError on 3.11 rather than returning 3 rows.
  5. Yielding during cleanup. Yielding inside except GeneratorExit raises RuntimeError, and a lock released only after that yield is never freed. Fix: release resources in finally with no yield.

Interview tips

Open with the contract. 'A comprehension is an eager loop folded into an expression. A generator is a paused frame that I resume one value at a time. The question is which contract I need: storage, replay, or when the work happens.'

Expected follow-ups

  • Is this pipeline streaming? Trace the chain to the final consumer and name any barrier.
  • What does send do? It sets the value of the suspended yield.
  • Why did the second loop print nothing? Iterators return themselves, and exhaustion is permanent.
  • How do you fail fast on bad input? The body runs at the first next(), so a try around the call catches nothing. Validate in a regular function that returns the generator.
  • A generator can be consumed once. For multi-pass aggregates over a one-shot fetch, compute all of them in one loop and keep only the rows you must return.
  • What does tee cost? Its buffer grows with the distance between branches.

30-second outline

  1. Name the contrast: eager container versus paused frame.
  2. Timing: a list runs every element at construction. A generator expression defers everything except the leftmost iterable.
  3. Consequence: memory and early exit. Generators win when the consumer stops early or the input is large.
  4. One trap and its fix, such as the one-shot reuse with a factory.
  5. The choice for this case, with the reason.

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.