Advertisement

Comprehensions & Generators interview questions and answers

15 Comprehensions & Generators interview questions for Python roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How would you implement a memory-efficient sliding window or batching generator over a large iterable?

Use itertools.islice() combined with a generator function (or the itertools 'batched' recipe/function in newer Python) to pull a fixed-size chunk from the source iterator at a time, yielding each batch as a tuple or list — advancing through the source lazily without ever holding the FULL dataset in memory.
from itertools import islice

def batched(iterable, size):
    it = iter(iterable)
    while batch := tuple(islice(it, size)):
        yield batch

for batch in batched(range(10), 3):
    print(batch)  # (0,1,2), (3,4,5), (6,7,8), (9,)
Real-world example
Processing a huge dataset (like database rows or log lines) in fixed-size batches for bulk API calls or bulk inserts.
Likely follow-ups
  • How does the walrus operator (:=) inside the while loop's condition make this batching implementation more concise?
functools & Functional Programming Tools
Q12 Advanced Save

How do you correctly close a generator early and ensure any try/finally cleanup inside it still runs?

Call generator.close() explicitly, or simply let the generator object be garbage collected (or go out of scope after a 'break' in a for loop) — both raise GeneratorExit inside the generator at its current yield point, which a try/finally block will still correctly execute, ensuring cleanup happens even on early termination.
def managed_resource():
    print("acquiring")
    try:
        yield "resource"
    finally:
        print("releasing")  # runs even if the consumer breaks out early or calls close()

gen = managed_resource()
next(gen)      # "acquiring"
gen.close()    # triggers GeneratorExit -> "releasing" prints
Real-world example
Guaranteeing a file handle or database cursor opened inside a generator is properly released even if the consumer stops iterating early.
Likely follow-ups
  • What happens if a generator's try/finally block itself tries to yield another value in response to GeneratorExit?
Exception Handling
Q13 Advanced Save

How would you implement a coroutine-style generator-based pipeline (the classic pre-async/await pattern) using multiple chained 'send()'-driven generators?

Build a chain of 'consumer' generators, each primed with next() and receiving values via .send() from an upstream stage, forwarding processed results downstream — this classic pattern (popularized by David Beazley's coroutine talks) predates async/await and demonstrates how generators alone can implement a full data pipeline with backpressure-free pushing.
def printer():
    while True:
        value = yield
        print(f"Got: {value}")

def filter_even(target):
    while True:
        value = yield
        if value % 2 == 0:
            target.send(value)

p = printer(); next(p)
f = filter_even(p); next(f)
for i in range(5):
    f.send(i)  # sends 0, 2, 4 through to the printer
Real-world example
Understanding the historical generator-based coroutine pattern that directly inspired and predates Python's async/await syntax.
Likely follow-ups
  • Why did Python eventually introduce dedicated async/await syntax instead of relying entirely on this generator-based coroutine pattern?
Concurrency (asyncio/threading/multiprocessing)
Q14 Advanced Save

How do you write a comprehension with MULTIPLE 'if' conditions, and how does that differ from combining them with 'and'?

Multiple consecutive 'if' clauses in a comprehension are implicitly combined with logical AND — functionally identical to combining the same conditions with an explicit 'and' in a single 'if' clause, so it's purely a stylistic choice which form to use.
result = [n for n in range(20) if n % 2 == 0 if n % 3 == 0]
print(result)  # [0, 6, 12, 18]

# Equivalent using a single 'if' with 'and':
result2 = [n for n in range(20) if n % 2 == 0 and n % 3 == 0]
Real-world example
Filtering a dataset by multiple independent criteria in a single, readable comprehension expression.
Likely follow-ups
  • Is there ever a meaningful PERFORMANCE difference between multiple 'if' clauses versus one combined 'and' condition?
Data Types & Structures
Q15 Advanced Save

How would you profile whether a generator expression is actually providing a measurable memory or performance benefit over a list comprehension in a specific use case?

Use the 'tracemalloc' module (or sys.getsizeof() for a rough comparison) to measure actual memory usage of a materialized list versus a generator object, and 'timeit' to compare execution time for the specific consuming operation — the benefit is usually most measurable for LARGE datasets combined with EARLY TERMINATION or streaming consumption, not for small collections consumed in full anyway.
import sys

list_version = [n * n for n in range(1_000_000)]
gen_version = (n * n for n in range(1_000_000))

print(sys.getsizeof(list_version))  # several MB
print(sys.getsizeof(gen_version))   # ~200 bytes, regardless of the range size
Real-world example
Deciding whether converting a hot-path list comprehension into a generator expression is actually worth the (minor) readability trade-off for a given dataset size.
Likely follow-ups
  • At roughly what collection size does the memory difference between a list and a generator become practically significant?
Debugging & Profiling

Showing 11–15 of 15