INSIGHTS
Software Development

Learn Python Generators and Yield: Improve Performance with Simple Examples

In this article
  1. Start with one generator and a visible state change
  2. Compare an eager list with an on-demand stream
  3. Stream a file safely and close it predictably
  4. Compose generators using yield from
  5. Bound memory, work and errors
  6. Generators, asynchronous functions and performance

A Python generator is an iterator that computes values when a caller asks for them. The yield statement suspends a function and preserves its local execution state. That can reduce peak memory compared with eagerly building a list, but it does not automatically make computation faster or remove the need to close files and release resources. These examples show when laziness is useful and how to avoid common mistakes.

Start with one generator and a visible state change

def countdown(start):
    while start > 0:
        yield start
        start -= 1

values = countdown(3)
print(next(values))  # 3
print(next(values))  # 2
print(list(values))  # [1]

Calling countdown(3) returns a generator object; the body has not executed yet. Each next() resumes execution from the previous yield. Once exhausted, the generator raises StopIteration, which a for loop handles automatically. Iterating over the same exhausted generator again does not restart it; create a new generator instead.

Compare an eager list with an on-demand stream

def squared_values(limit):
    for number in range(limit):
        yield number * number

print(sum(squared_values(5)))  # 30
print([x * x for x in range(5)])  # [0, 1, 4, 9, 16]

The generator version can feed values directly to sum without storing a separate list. The list comprehension is better when you need to index, inspect or traverse the values repeatedly. A generator expression, (x*x for x in range(5)), offers compact laziness without defining a named function. Choose based on the consumer’s requirements, not a blanket rule that generators are always superior.

Stream a file safely and close it predictably

def nonempty_lines(path):
    with open(path, encoding="utf-8") as stream:
        for raw_line in stream:
            text = raw_line.strip()
            if text:
                yield text

for line in nonempty_lines("notes.txt"):
    print(line)

The file is opened when the generator first starts advancing. The with block ensures that normal exhaustion or generator closure releases the file. If a caller abandons a partially consumed generator, explicitly close it or structure ownership around a context manager; do not assume that cleanup occurs at a predictable instant in every Python implementation. The code strips surrounding whitespace; if whitespace is meaningful, use a narrower newline-only trim.

Compose generators using yield from

def groups():
    yield from ("alpha", "beta")
    yield from ("gamma",)

print(list(groups()))  # ['alpha', 'beta', 'gamma']

yield from delegates iteration to another iterable. It is useful when a pipeline needs to combine sources without first creating a combined list. For large data processing, a sequence of small, readable generators can express parsing, filtering and transformation, but monitor whether an upstream resource remains open longer than expected.

Bound memory, work and errors

Lazy production is not the same as unlimited processing. A generator that feeds an unbounded source to list() or sorted() still accumulates all values. Use a deliberate consumer limit such as itertools.islice when exploring an infinite stream. If a generator raises an exception, the calling loop receives it; handle expected data errors at the appropriate boundary rather than quietly discarding corrupted records.

from itertools import islice

def natural_numbers():
    number = 1
    while True:
        yield number
        number += 1

print(list(islice(natural_numbers(), 4)))
# [1, 2, 3, 4]

Generators, asynchronous functions and performance

A regular generator uses yield to produce values during ordinary iteration. An async def function with yield creates an asynchronous generator, which is consumed with async for. The distinction matters: laziness alone does not schedule network requests concurrently. Async I/O has separate await and cancellation rules explained in the existing Python asyncio tutorial.

Measure real bottlenecks before optimizing. Generators may reduce memory pressure and improve clarity, but extra per-item Python overhead can make a short list faster. The official Python generator reference documents how iteration state is preserved and why generator functions automatically supply iterator methods.

Filed under Software Development