The mental model: pull-based lazy sequences
A generator is a function that remembers where it left off. Calling it does not run the body โ it returns an iterator object. Each call to next() resumes execution at the most recent yield, sends you the yielded value, and freezes again until the next pull. This pull-based laziness is what lets you write code that reads like it processes a million rows but actually holds one row in memory at a time. Interviewers ask about generators because they reveal whether you understand memory, control flow, and the difference between building a list and producing a stream.
Prerequisites
- !Functions, loops, and for statements
- !Basic familiarity with the yield keyword
What You'll Learn
- 1Explain the iterable versus iterator distinction with concrete classes
- 2Write generator functions and generator expressions and pick the right one
- 3Compose generator pipelines and reason about their memory usage
- 4Use yield from, send, and itertools to simplify complex iteration code
Iterable versus iterator: the distinction interviewers probe
An iterable is any object with __iter__ that returns an iterator โ lists, tuples, dicts, sets, strings, files, and your own classes if you implement the method. An iterator is an object with __next__ that returns the next value or raises StopIteration. A for loop calls iter() once to get an iterator and then calls next() repeatedly. Because iterators are stateful, they are single-use: once exhausted, you need a fresh one, which is why __iter__ on a container class should return a new iterator instance each time rather than returning self.
Implementing a custom iterator by hand is a classic warm-up. A Fibonacci iterator that carries its own two state variables and raises StopIteration after a count is reached demonstrates the full protocol in twenty lines. The subtlety interviewers listen for: if your class implements both __iter__ returning self and __next__, it is both iterable and iterator, and looping over it twice the second way yields nothing. Splitting the container and iterator into two classes avoids that trap and supports multiple simultaneous loops.
Generator functions versus generator expressions
A generator function looks like a normal function but contains one or more yield statements. A generator expression is the lazy sibling of a list comprehension, written with parentheses instead of brackets: (x * x for x in range(10_000_000)) produces one square per next() call and allocates essentially nothing up front. The rule of thumb is simple: use a list comprehension when you need the data more than once or need len(); use a generator expression when you will consume the values once and discard them.
Inside a generator function you can yield in a loop, yield conditionally, and delegate to sub-generators with yield from. Delegation flattens nested generators, forwards values without manual looping, and โ the detail candidates forget โ returns the sub-generator's return value, which surfaces in the StopIteration.value when the generator is exhausted. That mechanism is exactly how async for and various coroutine libraries are built on top of plain generators.
def fibonacci(limit):
"""Yield Fibonacci numbers lazily."""
a, b = 0, 1
count = 0
while count < limit:
yield a
a, b = b, a + b
count += 1
def read_lines(path):
"""Stream a large file without loading it into memory."""
with open(path, "r", encoding="utf-8") as handle:
for line in handle:
yield line.rstrip("\n")
squares = (x * x for x in range(1000000))
print(next(squares)) # 0
print(next(squares)) # 1
Pipelines: composable stages that scale to gigabytes
The real power of generators shows up when you chain them. A data pipeline might read rows lazily, filter them, transform the survivors, and batch them for insertion โ each stage a small generator that pulls from the stage before it. Because nothing is materialized, the pipeline processes a file of any size in constant memory. Interviewers love this pattern because it converts "how would you handle a 40 GB CSV on a laptop" from a scare question into a five-minute demo.
itertools supplies the industrial-strength versions. islice takes a window from the front of any iterable, chain concatenates several, groupby groups consecutive equal keys, accumulate produces running totals, and takewhile or dropwhile cut a stream on a predicate. Knowing even three of these lets you replace hand-rolled loops with declarative one-liners, which reads as production experience.
from itertools import islice, accumulate, groupby
from operator import itemgetter
def integers():
n = 1
while True:
yield n
n += 1
def squares(source):
for value in source:
yield value * value
pipeline = islice(squares(integers()), 5)
print(list(pipeline)) # [1, 4, 9, 16, 25]
sales = [("east", 10), ("east", 20), ("west", 5)]
for region, group in groupby(sales, key=itemgetter(0)):
total = sum(amount for _, amount in group)
print(region, total)
print(list(accumulate([1, 2, 3, 4]))) # [1, 3, 6, 10]
One-shot semantics and the restart problem
Because a generator is an iterator, it can be consumed only once. Code that accidentally iterates a stored generator twice silently processes nothing the second time โ a bug that shows up as empty reports rather than exceptions. The defensive fixes are to convert to a list when the data is small and needed repeatedly, or to store a factory function and call it for each fresh pass. In interviews, naming this failure mode before it bites you scores points; most candidates never mention it.
Garbage collection interacts with generators too. A suspended generator holds a reference to its frame, including local variables, so abandoning a half-consumed generator without closing it can keep large objects alive until the generator is collected. The explicit answers are calling close(), using the generator inside a with-style pattern, or ensuring the generator's locals do not pin the big data. CPython will collect an unreferenced generator and run its finally blocks, but relying on that is fragile in codebases that maintain reference cycles. Related: a finally inside a generator runs at close or collection, which makes it the right home for releasing file handles and locks held across yields โ a point that connects generators directly to the context-manager lesson.
Two-way communication with send
Generators can receive values as well as produce them. Calling gen.send(value) resumes the generator and delivers the value as the result of the yield expression. The standard dance is to prime the generator with next() once, then send inputs in a loop. A running-average coroutine that yields the current average and accepts the next sample is the canonical example. Before async/await landed, this mechanism powered async frameworks; today it remains a favorite interview topic because it tests whether you truly understand generator control flow.
def running_average():
total = count = 0
average = None
while True:
value = yield average
if value is None:
return
total += value
count += 1
average = total / count
calc = running_average()
next(calc) # prime
print(calc.send(10)) # 10.0
print(calc.send(20)) # 15.0
print(calc.send(30)) # 20.0
calc.close()
Choosing between generators, lists, and itertools
The table below captures the decision you should narrate when an interviewer asks how you would process a large collection.
| Situation | Preferred tool | Why |
|---|---|---|
| Data consumed exactly once | Generator function or expression | Constant memory, no up-front cost |
| Data reused or sized with len() | List comprehension | Materialized and reusable |
| Infinite or unbounded stream | Generator | Cannot materialize anyway |
| Need running totals, windows, grouping | itertools helpers | Battle-tested, fast C loops |
| Need to send values back in | send-capable coroutine generator | Bidirectional control flow |
| Multiple passes over cached data | Store a factory, call per pass | Avoids the one-shot trap |
Common Mistakes
Storing a generator in an instance attribute and iterating it from several methods
Fix: Store a factory function and create a fresh generator per consumption
Building an intermediate list inside every stage of a pipeline
Fix: yield lazily in each stage; only materialize at the very end if needed
Forgetting to prime a send-based generator before calling send
Fix: Call next() once, or wrap priming in a helper method
Using yield from on a plain iterable and expecting it to return a meaningful value
Fix: yield from propagates StopIteration.value only from a sub-generator
Best Practices
- State the memory profile of your solution โ interviewers ask about big inputs next
- Reach for itertools before hand-rolling loops over large collections
- Close generators you abandon early, or ensure their locals hold nothing expensive
- Name the one-shot limitation out loud whenever you store an iterator
Interview Questions
Q1: What is the difference between a generator function and a generator expression?
A generator function is an ordinary def containing yield; calling it returns a generator. A generator expression is a single expression in parentheses that produces a generator directly. Both create single-use lazy iterators.
Q2: How does Python's garbage collector handle a half-consumed generator?
When the generator object's reference count reaches zero, CPython closes it, running finally blocks and releasing the frame's locals. Circular references may delay this until the generational collector runs.
Q3: When would you use a list comprehension instead of a generator expression?
When you need multiple passes, random access, or len() โ for example sorting, deduplicating, or indexing the results. If the consumer walks the data once, a generator is almost always better.
Q4: Explain generator delegation with yield from.
yield from loops over the sub-iterator transparently, forwards yields in both directions for send-based coroutines, and propagates the sub-generator's return value into StopIteration.value.
Q5: How can you restart an exhausted generator?
You cannot rewind it. Store a function that creates a new generator and call it for each pass, or convert to a list if the dataset is small enough to hold.
Key Takeaways
- Iterables produce iterators; iterators are stateful and single-use
- Generators are iterators built by functions containing yield; expressions use parentheses
- Chained generators process huge files in constant memory
- itertools provides islice, chain, groupby, accumulate, takewhile, and more for industrial pipelines
- send enables two-way coroutines; close prevents lingering frames
- One-shot semantics are the most common generator bug โ name the fix before you need it