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.
Curated: · Written: · Reviewed:
MCQ-4A telemetry service normalizes a batch of sensor readings `xs = [4, -1, 7, -3]` before zipping them with their timestamps. Negative readings must be clamped to 0, and the output must keep one value per input so the zip stays aligned. Which expression produces the required list?
Answer to see the discussion.
MCQ-7A set comprehension normalizes 1,000 inputs, and the finished set holds 20 values. How many times does the normalization expression run?
Answer to see the discussion.
MCQ-2A team is refactoring `[f(x, y) for x in xs for y in ys(x) if keep(y)]` into explicit loops and must preserve how often `ys` is called and whether `keep` runs before `f`. Which expansion preserves the comprehension's behavior?
Answer to see the discussion.
MCQ-6A nightly job builds `index = {r['id']: enrich(r) for r in records}`, streaming `records` oldest first. Two records carry the id 'u-42': an earlier one with status 'open' and a later one with status 'closed', and every other id first appears after that pair. `enrich` calls a rate-limited API. Which description of `index` is correct?
Answer to see the discussion.
MCQ-3```python item = 100 def f(): squares = [item * 2 for item in range(3)] return squares, item print(f()) ``` What does the final `print` output?
Answer to see the discussion.
MCQ-21A class body binds `LIMIT = 5` and then evaluates `[i for i in range(LIMIT)]`, which raises `NameError: name 'LIMIT' is not defined` when the class is created; the same comprehension inside a method of that class, with `LIMIT` bound as a local of the method, runs fine. Which statement explains the difference?
Answer to see the discussion.
MCQ-5A function evaluates `[y for x in rows if (y := parse(x)) is not None]` and then references both `x` and `y` on the following lines. Which statement describes what the enclosing scope sees once the comprehension completes?
Answer to see the discussion.
MCQ-1This runs against ten million rows, and the first row with `score > 0.9` is row 3: ```python def first_match(rows): hits = [r for r in rows if r.score > 0.9] print("built") return next(iter(hits)) ``` `"built"` prints after about four seconds, and `next` returns immediately. What explains the four seconds?
Answer to see the discussion.
MCQ-20A service scans a log with `any(pred(line) for line in lines)`; on requests where `pred` matches within the first few lines it returns far sooner than the equivalent `any([pred(line) for line in lines])`. Why?
Answer to see the discussion.
MCQ-8`gen = (parse(line) for line in open(path))` raises `FileNotFoundError` on the assignment line, and `parse` has not been called. Why?
Answer to see the discussion.
MCQ-12A generator function is used to manage a complex, multi-step data pipeline where intermediate state must be preserved across multiple calls to the iterator. Which mechanism allows the generator to suspend execution and resume precisely at the point of suspension?
Answer to see the discussion.
MCQ-9A generator object is passed to two consumers in sequence. The first consumer runs a for loop over it to completion; the second consumer's for loop body never executes. What explains why the second consumer sees no values?
Answer to see the discussion.
MCQ-10A `SocketReader` is a plain class (not a generator) whose `__iter__` returns `self` and whose `__next__` pulls the next chunk from a socket. Callers iterate it with plain `for chunk in reader:` loops they cannot modify. What must `__next__` do when the socket reports EOF so those loops end cleanly?
Answer to see the discussion.
MCQ-14A batch job runs on Python 3.11 and pulls rows from a cursor with this generator: ```python def first_n(rows, n): it = iter(rows) for _ in range(n): yield next(it) ``` The cursor for one shard holds 3 rows, and the job calls `list(first_n(cursor, 5))`. What does the job observe?
Answer to see the discussion.
MCQ-15A generator is defined by `def stage(): total = 0` followed by `while True: chunk = yield total; total += chunk`; a caller creates `g = stage()` and then runs `for batch in batches: g.send(batch)`. The first `g.send(batch)` raises, and every batch must still reach the stage through `send`. Which statement names the exception and the single call that must run before the loop?
Answer to see the discussion.
MCQ-16CPython 3.12. A generator is suspended at a `yield` inside a `try` block. The caller invokes `throw` with a `ValueError`; the generator's `except ValueError` clause catches it and executes another `yield` before the generator is resumed again. What does the `throw` call return, and what state is the generator left in?
Answer to see the discussion.
MCQ-18A generator delegates to a subgenerator and reports what the subgenerator returned (Python 3.12): ```python def child(): total = 0 count = 0 while True: x = yield total if x is None: break total += x count += 1 return count def outer(): result = yield from child() yield f'received {result} values' g = outer() print(next(g)) print(g.send(10)) print(g.send(5)) print(g.send(None)) ``` What does the fourth `print` output?
Answer to see the discussion.
MCQ-13A worker generator ends with `return summary`; a wrapper does `result = yield from worker()` and then `return result`. The consumer is `for row in wrapper(): print(row)`, and `summary` never prints. The team wants to keep both `return` statements as termination values. Which change lets the caller of `wrapper()` obtain `summary`?
Answer to see the discussion.
MCQ-11A Python 3.12 service has this generator: ```python def stream_rows(path): f = open(path) header = f.readline() if header != "id,name\n": raise ValueError("bad header") for line in f: yield line ``` A request handler runs `rows = stream_rows("bad.csv")` inside `try/except ValueError` that returns HTTP 400. The handler logs `created`, stores `rows` on the response object, and returns. The framework iterates `rows` 200 ms later while writing the body. Where does the `ValueError` surface?
Answer to see the discussion.
MCQ-17A generator acquires a `threading.Lock`, yields rows, and in its `except GeneratorExit` handler yields one final audit row and then releases the lock. A caller that has read enough rows calls `gen.close()`; CPython raises `RuntimeError: generator ignored GeneratorExit` and the lock is never released. The lock must be released at the moment the caller abandons iteration. Which change achieves that?
Answer to see the discussion.
MCQ-19A pipeline ends in `sorted(generator)`. Can it still claim bounded streaming memory?
Answer to see the discussion.
MCQ-24A metrics worker polls a source exposed as `itertools.count()`: an open-ended counter that never signals a stop. A teammate changes the consumer to `rows = list(source)` before aggregating. What happens to the worker?
Answer to see the discussion.
MCQ-23A batch job reads order records in the order they were written and calls itertools.groupby(records, key=lambda r: r['customer_id']) to build per-customer batches. The output contains several groups for the same customer ID. Which precondition was missing?
Answer to see the discussion.
MCQ-22A job feeds one generator over a multi-gigabyte log file into `itertools.tee` and drives two branches from it: one counts records and finishes in seconds, the other POSTs each record to a rate-limited collector and stays hours behind. As that gap widens, which cost actually grows?
Answer to see the discussion.
MCQ-25A Python 3.12 handler fetches a 24 MB CSV (200,000 rows) from an upstream endpoint that closes the connection once the body is read; the fetch takes 700 ms and the endpoint is billed per request. The handler must compute three aggregates over every row and then return row 150,000 to a paginated endpoint. It builds `rows = (parse(line) for line in resp.iter_lines())`, passes `rows` to each aggregator in turn, then walks `rows` to row 150,000. The first aggregate is correct, the second and third return 0, and the row lookup raises StopIteration. Materializing all 200,000 parsed rows costs about 40 MB and the container limit is 256 MB. What change fixes this?
Answer to see the discussion.