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
- A function with
yieldinside becomes a generator function. Calling it does not run its body (the code inside it) yet.cook(...)only makes a generator object: a kitchen that is ready but has not cooked anything yet. If you print it,print(kitchen)writes<generator object cook at 0x...>. That is whykitchen readyprints first. next(kitchen)is the waiter's call "next!". It runs the body until it reaches ayield.yield itemgives youitemas the result ofnext, then the function stops right there. The variables inside keep their values.- The next
next(kitchen)continues right after thatyield, into the next round of the loop. - This way of working is called lazy: a value is only computed when you ask for it.
- Compare this with a normal function that collects the items with
result.append(item)and thenreturn result. As soon as you call it, it runs all the way toreturn. So all threecooking ...lines print first, thenkitchen ready.
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
forcallsnext()for you, and stops quietly atStopIteration, with no error.- In the output, the
cookingandservinglines take turns: each item is only cooked when the loop asks for it. - A generator can be used only once. The second
forloop prints nothing, because the generator is used up. Need it again? Callcook(...)again to make a new generator. list(kitchen)and[x for x in kitchen]use up a generator too: both collect all its values into a list.
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 |
- The right side,
b, a + b, is computed first with the old values, then stored inaandb. Soa + bstill uses the olda, and you need no temporary variable to keep it. _is an ordinary variable name, used when the value is not needed.for _ in range(5)means "repeat 5 times".- The numbers in the
acolumn are the sequence: 0, 1, 1, 2, 3. If youyieldaon every round, the result is a Fibonacci generator.
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
[...](a list comprehension) is eager: every value is computed now and stored in memory.(...)is lazy: values are computed one at a time, when asked for.sum(raised)only adds up what is left, 7 + 14, becausenextalready took 17.{x * 2 for x in ...}(a set comprehension) andlist(map(...))are eager too: everything is computed and stored at once.
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
- Thinking a call runs the generator.
cook(orders)by itself prints nothing. The body only runs whennext(),fororlist()asks for a value. - Using a generator twice. The second loop is empty, and a second
list(kitchen)is[]. Make a new generator, or store the values in a list when you really need them again. - Writing
returnwhereyieldbelongs. The function stops at the first value and is no longer a generator. In the exercise,[x for x in fibonacci(10)]then fails withTypeError: 'int' object is not iterable. - Treating a generator like a list.
len(kitchen)raisesTypeError: object of type 'generator' has no len(), andkitchen[0]raisesTypeError: 'generator' object is not subscriptable. Need the length or an index? Convert it to a list first:list(kitchen).
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.