Unlocking Python's Secret Weapon: How `yield` Produces Values on Demand

This article examines how Python generators and the yield keyword produce values on demand, measures their memory cost against lists and describes their main pitfalls.

A green tree python coiled in neat loops around a branch, its head resting on its coils against a dark background
Photo by Tirza van Dijk on Unsplash

The present article addresses generators and the yield keyword, which together constitute one of the most effective mechanisms that Python offers for processing large volumes of data without exhausting memory. The problem they solve is a familiar one: a program that builds a complete collection before using it must keep every element in RAM at the same time, and that cost grows linearly with the size of the data. A generator follows the opposite strategy, since it computes each value only when it is requested and then suspends its execution until the next request. This is the secret weapon that the following sections examine, measure and delimit.

Collections Built in Advance and Their Cost

The conventional way of producing a sequence consists in building the complete collection and returning it only when it is finished. A function of this kind, which computes the squares of the first ten million integers, is shown below.

def get_squares_list(limit):
    squares = []
    for number in range(limit):
        squares.append(number * number)
    return squares

# Expensive: with limit = 10_000_000 this call reaches about 400 MB of RAM.
squares = get_squares_list(1_000)
print(len(squares))  # Output: 1000

The function is correct, but the caller receives nothing until the last element has been computed, and at that moment every element is held in memory. A measurement with tracemalloc on CPython 3.12 shows that a list of ten million squares reaches a peak of approximately 409 MB. This figure deserves a clarification, because sys.getsizeof reports only 89 MB for the same list: that function counts the array of references, not the integer objects to which they point. Consequently, tracemalloc is the appropriate tool when the real cost of a collection must be established.

How yield Produces Values on Demand

The present section shows how the same sequence is produced by a generator. It is sufficient to replace the accumulation in a list with the yield statement; a message printed inside the function reveals, in addition, the moment in which its body is executed.

def generate_squares(limit):
    print("Body started")
    for number in range(limit):
        yield number * number

squares = generate_squares(10_000_000)
print(type(squares).__name__)  # Output: generator

print(next(squares))  # Output: Body started, then 0
print(next(squares))  # Output: 1
print(next(squares))  # Output: 4

The output corroborates three facts. First, calling generate_squares does not execute a single line of its body; it only returns a generator object. Second, the body starts at the first call to next(), which runs it until the first yield and delivers that value. Third, each subsequent call computes exactly one new square, so the ten million values are never present at the same time, and the call with limit = 10_000_000 is therefore inexpensive.

Certain game universes work in the same way: a planet does not exist in memory until a traveller arrives at it, and the rest of the galaxy remains a mere possibility. This means that a generator does not hold its sequence at all, but only the recipe and the current position needed to produce the next element. The mechanism behind this behaviour consists of two phases, which are the following:

  1. Suspension. When execution reaches a yield, the value is delivered to the caller and the function is frozen, together with its local variables and the exact point at which it stopped.
  2. Resumption. The next request, made with next() or by the following iteration of a for loop, resumes the function from that point until it reaches the next yield or ends.

This cycle is known as lazy evaluation, since no work is performed until a value is required. Between two requests, the function remains suspended, much like a soldier who enters cryosleep with the request "wake me when you need me". The analogy of the unvisited planet, however, stops at this point: a planet can be visited again and keeps its appearance, whereas a generator advances in a single direction and cannot return to a value it has already delivered, a limitation that is described in the section devoted to pitfalls.

Generator Expressions and Their Measured Cost

Generator expressions are the compact form of a generator, and their syntax is identical to that of a list comprehension, with parentheses in place of square brackets. Both forms are compared below with one million elements, using tracemalloc to record the peak of memory that each one reaches.

import sys
import tracemalloc

tracemalloc.start()
squares_list = [n * n for n in range(1_000_000)]
list_peak = tracemalloc.get_traced_memory()[1]
del squares_list
tracemalloc.stop()

tracemalloc.start()
squares_gen = (n * n for n in range(1_000_000))
gen_peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()

print(f"List peak:      {list_peak / 1e6:.1f} MB")  # Output: about 40.4 MB
print(f"Generator peak: {gen_peak} bytes")          # Output: a few hundred bytes
print(sys.getsizeof(squares_gen))                   # Output: about 200

The results show that the list requires about 40 MB for one million elements, whereas the generator expression occupies a few hundred bytes, a size that does not depend on the length of the sequence. The exact figures vary slightly between Python versions and platforms, but the order of magnitude does not. It must be noted, on the other hand, that the advantage of generators lies in memory and in the time until the first value, not in total throughput: on the same machine, sum([n * n for n in range(1_000_000)]) took 0.059 s and sum(n * n for n in range(1_000_000)) took 0.049 s, two results of the same order. When a generator expression is the only argument of a function, as in the second case, the additional parentheses can be omitted.

Generator Pipelines

Generators can also be composed into pipelines, in which each generator consumes the output of the previous one and processes a single element at a time, so that no intermediate collection is ever built. In the code that follows, the lines of a text source are filtered and transformed in this way; the source is simulated with io.StringIO so that it does not depend on any file.

import io
from itertools import islice

log = io.StringIO("INFO start\nERROR disk full\nINFO retry\nERROR timeout\n")

def read_lines(source):
    for line in source:
        yield line.rstrip("\n")

def only_errors(lines):
    for line in lines:
        if line.startswith("ERROR"):
            yield line.removeprefix("ERROR ")

for message in only_errors(read_lines(log)):
    print(message)
# Output: disk full
# Output: timeout

def even_numbers():
    number = 0
    while True:
        yield number
        number += 2

print(list(islice(even_numbers(), 5)))  # Output: [0, 2, 4, 6, 8]

Two aspects of this example are particularly relevant. On the one hand, a file object is already a lazy iterator in Python, so the value of the pipeline does not lie in reading line by line, but in the filtering and transformation stages that are added without building intermediate lists. On the other hand, the generator even_numbers never ends, which is legitimate as long as the consumer limits it; itertools.islice takes the first five values and leaves the rest uncomputed, whereas list(even_numbers()) would never return.

When a generator must deliver every value of another iterable, the expression yield from, introduced by PEP 380 in Python 3.3, replaces the explicit loop, as the following example shows.

def chain_all(*iterables):
    for iterable in iterables:
        yield from iterable

print(list(chain_all([1, 2], (3,), range(4, 6))))  # Output: [1, 2, 3, 4, 5]

The function delegates to each iterable in turn, and yield from also transmits the values sent with send() and the exceptions raised with throw(), which makes it more than an abbreviation of the for loop.

Known Bugs: Pitfalls of Generators

This section identifies the limitations that most frequently produce errors in code that uses generators. Four pitfalls are distinguished, which are the following:

  1. Exhaustion. A generator can be traversed only once. A second traversal produces nothing and raises no error, which makes this the most silent of the four.
  2. No length and no indexing. len() and squares[10] raise TypeError, because the values do not exist until they are produced.
  3. Return values. A return value inside a generator does not deliver that value to a for loop; it travels in the value attribute of the StopIteration exception, and yield from receives it as the result of the expression.
  4. StopIteration inside the body. Since Python 3.7, as established in PEP 479, a StopIteration that escapes the body of a generator, for example from a bare next() on an empty iterator, is converted into RuntimeError.

The first three pitfalls are reproduced in a single example, built around a generator that yields two processing stages and then returns a final status.

def stages():
    yield "stage 1"
    yield "stage 2"
    return "done"

steps = stages()
print(list(steps))  # Output: ['stage 1', 'stage 2']
print(list(steps))  # Output: [] (the generator is exhausted)

try:
    len(stages())
except TypeError as error:
    print(error)  # Output: object of type 'generator' has no len()

run = stages()
next(run)
next(run)
try:
    next(run)
except StopIteration as stop:
    print(stop.value)  # Output: done

The second call to list() returns an empty list because the generator had already been consumed; when a sequence must be traversed several times, a list or a function that creates a new generator on each call is required. A related aspect concerns the release of resources: a generator that is abandoned before its end only executes its finally block when it is closed, either explicitly with close() or when it is garbage-collected. For this reason, a generator that opens a file or a connection should be consumed completely or closed explicitly, and the resource should preferably be managed with a with statement inside the generator.

When to Use Generators and When Not To

Consequently, the choice between a generator and a list does not depend on the size of the data alone, but on the way in which that data is consumed. The criteria are summarized in the following table.

Situation Recommended choice
Large or unbounded sequence traversed once Generator
Processing a file, a stream or query results element by element Generator or pipeline of generators
The first results are needed before the whole sequence is computed Generator
The data is traversed several times List
Access by index, slicing or len() is required List
Small collection whose cost in memory is negligible Either; a list is usually simpler to inspect

It follows from the table that the generator is the appropriate tool when the cost of keeping the data in memory exceeds the convenience of having it all at once. For small collections, the difference in memory is irrelevant, and the list offers random access and the possibility of repeated traversal without additional design.

Conclusion

It is concluded that yield turns an ordinary function into a producer of values on demand, whose memory remains of the order of a few hundred bytes regardless of the length of the sequence, as the measurements of this article corroborate. This secret weapon does not make computation faster in general, but it allows a program to start working immediately and to process data that would not fit in memory. Its magic, however, comes with precise rules: a generator is traversed only once, it has no length, and its resources must be released explicitly when it is abandoned. Generators also accept values through send(), a capability that turned them into the foundation of coroutines and that is developed in a future article of this series.