A Python generator produces values as they are requested rather than constructing an entire result list before a caller can start reading it. That makes generators useful for large inputs and composed processing steps, but it does not make them inherently faster, automatically asynchronous, or safe to replay. Understanding their lifecycle matters more than memorizing the yield keyword.
For learners preparing for the PCAP Python examination, the core ideas are the iterator protocol, generator functions and expressions, exhaustion, and when laziness changes program behavior. The examples below use ordinary Python 3 and can be run directly.
An iterator is a protocol, not simply a collection
An iterable supplies an iterator through iter(obj). The iterator returns its next item through next(it), which invokes its __next__() method. When no items remain, it raises StopIteration. An iterator also provides __iter__(), normally returning itself. A generator object already implements those methods; a custom iterator class must implement the appropriate protocol itself.
values = iter([4, 7])
print(next(values)) # 4
print(next(values)) # 7
# A third next(values) raises StopIteration
An iterable such as a list can provide a fresh iterator for each loop. A single generator object is one pass unless your code creates a new generator. Confusing those two behaviors is a common source of missing results in data pipelines.
The first yield suspends a function instead of finishing it
Calling a function that contains yield returns a generator object without executing its body immediately. Execution begins on the first request for a value, pauses at each yield, and resumes with its local variables intact. Reaching the end finishes the iterator; a return can end it early. The body does not run to completion at construction time.
def countdown(start):
while start > 0:
yield start
start -= 1
steps = countdown(3)
print(next(steps)) # 3
print(list(steps)) # [2, 1]
print(list(steps)) # []
This example shows both suspension and exhaustion. The last list is empty because the generator was already consumed. To rerun the sequence, call countdown(3) again. A function definition is reusable; an existing generator instance is not reset by looping over it again.
Laziness reduces buffering, but not every kind of cost
If a program must examine a million records one at a time, a generator can prevent the extra allocation of a list containing all transformed records. It does not remove the cost of reading each record, storing state elsewhere, or holding external resources open. A generator may be slower than a list comprehension for small inputs, and a downstream call to list(generator) materializes everything anyway.
squares = (x * x for x in range(5))
print(next(squares)) # 0
print(sum(squares)) # 30; the remaining 1, 4, 9, 16
A generator expression uses parentheses and evaluates elements lazily, whereas a list comprehension constructs a list at once. The right choice depends on whether you need random access, repeated passes, all results at once, or early termination after finding a match.
Read a file incrementally and close it reliably
A generator is valuable when one record can be processed before the next arrives. But a file handle is a resource, not simply an iterable. If a generator owns an open file and its caller stops early, cleanup timing must be deliberate. Prefer explicit ownership of the file, for example by keeping a with block around consumption. When a generator itself acquires a resource, use try/finally and close the generator at early exit where necessary.
from pathlib import Path
def nonempty_lines(lines):
for line in lines:
value = line.strip()
if value:
yield value
with Path("events.txt").open(encoding="utf-8") as stream:
for record in nonempty_lines(stream):
print(record)
if record == "STOP":
break
The context manager closes the file even if the loop exits on the marker. This is safer than assuming a generator will immediately be garbage-collected after the caller stops consuming it.
Compose operations with yield from, and keep ownership clear
Use yield from iterable when a generator should delegate iteration to another iterable. It is especially readable for flattening a small nested structure or composing independent sources. It is not a general guarantee of increased speed or reduced memory use; the processing inside each stage still determines the costs.
def flatten(groups):
for group in groups:
yield from group
print(list(flatten([[1, 2], [], [3]]))) # [1, 2, 3]
A multi-stage generator pipeline can apply filters before mapping values without storing all intermediate results. Yet pipelines require thought about one-shot inputs, exceptions, ordering, and whether a downstream consumer may unexpectedly request the stream twice. If multiple consumers need the same results, deliberately cache or regenerate them rather than sharing a consumed iterator.
Exceptions, close and a correct end-of-stream contract
A normal for loop handles StopIteration automatically. Calling next() yourself means you must either catch it or supply the optional default argument. Do not write a generator that raises StopIteration directly to end itself: in modern Python, an unintended StopIteration escaping from a generator body becomes a RuntimeError. Use return or let the function finish.
it = (n for n in range(2))
print(next(it, "done")) # 0
print(next(it, "done")) # 1
print(next(it, "done")) # done
A generator may also support send(), throw() and close(). These are advanced controls, not a reason to use generators for ordinary data traversal. close() requests finalization and executes finally cleanup; if the caller owns a resource, its lifecycle must still be managed explicitly. Use contextlib.closing when a closeable iterator needs deterministic cleanup.
Synchronous generators are not async generators
A conventional yield generator runs when a synchronous caller requests its next value. It does not itself perform nonblocking network I/O. Modern asyncio uses native coroutines created with async def and await; an async generator is written with async def plus yield and consumed using async for. Generator-based coroutines exist in Python history, but readers should not confuse them with recommended native async patterns.
If an asynchronous generator is stopped early, it may need an explicit aclose() or an async with contextlib.aclosing(...) wrapper to run finalizers in the right context. Backpressure in an application comes from the surrounding request/queue protocol and consumer behavior; a plain generator does not impose network flow control automatically.
Three exercises that test real understanding
First, implement a generator that yields only valid integer records from a file-like iterable. Test empty input, malformed records, early exit and a repeated second pass. Second, compare a list comprehension with a generator expression for a moderately large sequence using a memory profiler; separately measure execution time, because the resource tradeoffs are not identical. Third, write a chained generator pipeline that filters and normalizes log events, then test what happens when an exception occurs midway and the input cannot be replayed.
Generators solve a precise problem: they let a caller ask for the next item while preserving the producer’s state. Choose them when progressive consumption, resource efficiency or composable iteration matters. Choose materialized structures when multiple passes, indexing, or a stable snapshot matters. Always test exhaustion, cleanup, and failure behavior, not only the happy path.
Test that side effects happen at the time you expect
Because a generator does not execute until iteration begins, logging, network calls, writes and exceptions inside its body occur during consumption—not when the generator object is created. This timing surprises code that builds a generator, assumes it has completed the work, and only later loops over it. Test lazy side effects with a small counter or log and make transaction boundaries explicit.
A useful guardrail is to keep write operations outside a simple transformation generator, or to make the execution boundary clear in the calling code. If a database query or request owns a connection, define who closes it and what happens when the caller stops halfway. For a reusable computation, expose a factory function that creates a new generator on each call rather than promising that one instance can be traversed twice.