Chapters & contents Lesson 20 of 20
3 min read
Python and practical programmingExpanded reading

Generators make the next value when it is needed

Trace suspension, exhaustion, and the difference between a recipe and a stored collection.

What you’ll learn

  • Explain what calling a generator function creates
  • Trace next calls across yield points
  • Recognize one-pass consumption and retained resource lifetime

Separate a collection from a sequence of work

A list stores references to its elements and can be traversed repeatedly. A generator offers values through the iterator protocol while its body executes as iteration requests them. Calling a function containing yield returns a generator object; it does not immediately run the whole body and collect every result. This difference is useful when processing a stream of records or stopping after a small number of matches. It is also a source of confusion when a learner expects a reusable collection.

Trace the suspension points

Consider a generator that loops over [2, 5, 8], yields value times two, and continues on the next request. Creating the generator performs no loop iterations. The first next call produces 4 and suspends at the yield. The second produces 10, and the third produces 16. A further next call raises StopIteration because the function has finished. A for loop handles normal iterator exhaustion for you. The generator retains the local state needed to resume, rather than restarting from the function’s first line after each yield.

python · Worked example
def doubled(values):
    for value in values:
        yield value * 2

g = doubled([2, 5, 8])
print(next(g))  # 4
print(list(g))  # [10, 16]
print(list(g))  # []

Consumption changes what remains

If you pass that generator to list, the list constructor consumes its remaining values. Passing the same exhausted generator to list again returns an empty list. This is expected stateful behavior, not a disappearing-data bug. To obtain a fresh traversal, call the generator function again or deliberately store the results when reuse is required. Assigning a second variable to the same generator object does not create an independent traversal; both names advance the same underlying iterator.

Laziness changes resource and error timing

A generator can reduce the need to build a large intermediate list, but it is not automatically free of memory costs. It can retain references in its local state, and a caller can still accumulate all yielded values. Errors inside its body may occur during iteration rather than when it is created. If iteration reads a file, design the file’s lifetime explicitly, for example by consuming the iterator inside the with block that owns the file. Do not assume delayed work has already completed successfully.

Choose a clear return contract

A helper returning a list promises materialized results. A helper returning an iterator promises a way to obtain values, often once, with work possibly still pending. Document the distinction when a caller might count results and then loop over them. Start experiments with a tiny generator and print messages before and after yield to see execution order, then remove the diagnostic prints. Once suspension is understandable, filtering large logs becomes a composition of small operations rather than an unexplained performance trick.

Try it yourself

Create g = doubled([2, 5, 8]), then run next(g), list(g), and list(g). Predict all three results and explain how to obtain all three doubled values again.

Show a possible solution

The results are 4, [10, 16], and []. The first next consumes one value, the first list consumes the rest, and the second list sees exhaustion. Call doubled([2, 5, 8]) again to create a fresh generator, then consume it.

Check your understanding

Try 14 questions across python and practical programming. Read each explanation and revisit anything that needs another pass.

Practise this subject

Go to the source

Use these primary references to check details and explore the topic further.

Saved in this browser. Signed-in progress syncs to your account.