Generators & yield — Python

A generator is a function with yield that produces its values one at a time. Calling it only makes a generator object: its body (the code inside it) does not…

A function that returns a list makes all its values first, then gives them to you. For three menu items, that is no problem. For ten million numbers, the list uses about 89 MB of memory, even though all you want is to add them up one at a time.

Mr. Darto's kitchen can work in two ways. The first way: every order is cooked at the start, then placed in a row on the table. The table gets full, and the first customer waits until everything is ready. The second way: the cook makes one order each time the waiter calls "next!", then waits for the next call. A normal function that returns a list is the first way, and the full table is its memory. A generator is the second way: a function that produces its values one at a time, only when asked. It does not prepare them all at once.

yield: pausing for a moment

The generator cook below prints cooking ... before it gives each item. Before you look at the output, guess: is the first printed line cooking coffee with milk or kitchen ready?

def cook(orders):
    for item in orders:
        print("cooking", item)
        yield item

kitchen = cook(["coffee with milk", "sweet tea", "toast"])
print("kitchen ready")
print(next(kitchen))
print(next(kitchen))

The output:

kitchen ready
cooking coffee with milk
coffee with milk
cooking sweet tea
sweet tea

This table follows each call, with two more next calls that the next section explains:

Call What runs inside cook Result
cook([...]) nothing yet a generator object
1st next(kitchen) print cooking coffee with milk, stop at yield coffee with milk
2nd next(kitchen) continue into the second round, stop at yield sweet tea
3rd next(kitchen) third round, stop at yield toast
4th next(kitchen) the loop is done, the function ends StopIteration

Used up: StopIteration

Add two more print(next(kitchen)) lines at the end of the cook program above. The third call still gets toast, but the fourth call gets no value:

kitchen ready
cooking coffee with milk
coffee with milk
cooking sweet tea
sweet tea
cooking toast
toast
Traceback (most recent call last):
  File "/home/darto/stall.py", line 11, in <module>
    print(next(kitchen))
          ~~~~^^^^^^^^^
StopIteration

StopIteration means the generator is finished, or used up: there is no yield left to reach.

Used in a for, and only once

Usually you do not call next() yourself: you go through a generator with for. This code goes through kitchen twice:

kitchen = cook(["coffee with milk", "sweet tea", "toast"])
for item in kitchen:
    print("serving", item)
print("second round:")
for item in kitchen:
    print("serving", item)
print("done")

The output:

cooking coffee with milk
serving coffee with milk
cooking sweet tea
serving sweet tea
cooking toast
serving toast
second round:
done

The Fibonacci sequence: shifting two numbers

The exercise of this lesson uses the Fibonacci sequence. In this sequence, each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, and so on. Two variables are enough to compute it, a and b. Both are shifted on every round: a takes the value of b, and b becomes a + b. This code does it with the unpacking from the tuple lesson:

a, b = 0, 1
for _ in range(5):
    print(a, b)
    a, b = b, a + b
Round a b After a, b = b, a + b
1 0 1 a = 1, b = 0 + 1 = 1
2 1 1 a = 1, b = 1 + 1 = 2
3 1 2 a = 2, b = 1 + 2 = 3
4 2 3 a = 3, b = 2 + 3 = 5
5 3 5 a = 5, b = 3 + 5 = 8

Generator expressions

A generator expression is written like a list comprehension, but with round brackets. The result is a generator:

prices = [15, 5, 12]
raised = (p + 2 for p in prices)
print(next(raised))   # 17
print(sum(raised))    # 21

You notice the difference between eager and lazy with big data. These numbers were measured on 64-bit Python 3.13:

import sys
big_list = [x ** 2 for x in range(10_000_000)]
gen = (x ** 2 for x in range(10_000_000))
print(sys.getsizeof(big_list))  # 89095160
print(sys.getsizeof(gen))       # 200

sys.getsizeof(x) gives the number of bytes of memory that x uses. The line import sys makes sys ready to use (the modules lesson covers it later). The list takes about 89 MB. The generator takes only 200 bytes, however long the sequence is. The underscores in 10_000_000 only separate the thousands, to make the number easy to read.

⚠️ Generators that do nothing, are used up, or are mistaken for lists

TL;DR: A generator is a function with yield that produces its values one at a time. Calling it only makes a generator object: its body (the code inside it) does not run yet. next() runs the body up to the next yield, gives you the value at that yield, then pauses there. When no yield is left, you get StopIteration. for calls next() for you and stops with no error when no values are left. Generators are lazy (a value is computed only when asked for) and can be used only once. A generator expression (x * 2 for x in ...) is lazy and uses little memory, while [...], {...} and list(map(...)) are eager (every value is computed at once). The Fibonacci sequence (each number is the sum of the two before it) is computed by shifting two variables: a, b = b, a + b.

⚡ yield: pausing for a moment

Write:

def cook(orders):
    for item in orders:
        print("cooking", item)
        yield item

kitchen = cook(["coffee with milk", "sweet tea", "toast"])
print("kitchen ready")
print(next(kitchen))
print(next(kitchen))
Guess first: is the first printed line cooking coffee with milk or kitchen ready?

kitchen ready. Because it has a yield inside, cook is a generator. Calling cook(...) doesn't run the code inside it yet. It only makes a generator object.

Meaning: next(kitchen) runs the code inside the function up to yield, gives you the value at that yield, then pauses there. The next next continues right after that yield. Values are only computed when asked for: that's what lazy means.

⚡ Only usable once

Guess first: you go through the same generator kitchen twice with for. What does the second loop print?

Nothing. A generator can be used only once, and kitchen was used up by the first loop.

Meaning: for calls next() for you, and stops with no error when it reaches StopIteration (the sign that no values are left). Need it again? Call cook(...) again to make a new generator.

⚡ Round brackets are lazy

Write:

prices = [15, 5, 12]
raised = (p + 2 for p in prices)
print(next(raised))   # 17
print(sum(raised))    # 21

Meaning: (...) is a generator expression: lazy, its values computed one at a time. sum(raised) only adds up what is left, 7 + 14, because next already took 17. [...] is eager: everything is computed now and stored. For ten million numbers, the list takes about 89 MB, the generator 200 bytes.

What you will learn