Generators: functions that pause with yield
🌍 In real life. A grandmother tells you one chapter of a long story each night. When you ask for more, she doesn't start again from the beginning: she remembers exactly where she stopped, like a bookmark, and carries on from there.
A generator function works like her. It is a normal def with yield inside instead of (or as well as) return:
- calling it doesn't run the body: it gives back a generator, paused before the first line
- each
next()runs the body until the nextyield, hands out that value, and pauses with a bookmark - the next
next()carries on right after thatyield - when the function ends,
next()raises StopIteration, like any iterator
The idea in one sentence: a function with yield in it is a generator function: calling it gives a paused generator, and each next() runs it to the next yield, hands out that value, and pauses again.
Its words:
yield: hand out one value and pause, keeping every local variable- generator: the paused function, which is also an iterator
- lazy: values are made only when asked for
def story():
print("(opening the book)")
yield "Chapter 1: the village"
yield "Chapter 2: the river"
yield "Chapter 3: the tiger"
book = story()
print("Got the book")
print(next(book))
print(next(book))
for chapter in book: # a for loop asks for the rest
print(chapter)yield vs return, step by step:
returnhands back one answer and the function is finished; its local variables are goneyieldhands back one of many answers and the function only pauses; its local variables stay, ready for the next round- a generator can only be gone through once, like any iterator; call the function again for a fresh one
def countdown(n):
while n > 0:
yield n
n = n - 1
yield "Lift off!"
print(list(countdown(3)))
print(list(countdown(1)))Why generators? A function that builds a list of a million items needs memory for all of them before you see the first. A generator hands them out one at a time, so it uses almost no memory, can start answering at once, and can even describe a sequence that never ends.
Mistakes and edge cases.
- Expecting the body to run at the call.
story()runs nothing; onlynext()(or a loop) does. - Asking for its length or an index.
len(g)givesTypeError: object of type 'generator' has no len(), andg[0]givesTypeError: 'generator' object is not subscriptable. Uselist(g)if you really need them. - Looping twice. The second loop finds the generator used up; call the function again for a fresh one.
- return with a value. A
returninside a generator just ends it; the value isn't handed out bynext().
Quiz
What does this print?
def colours(): yield "red" yield "green" c = colours() print(next(c), next(c))What does this print?
def numbers(): print("start") yield 1 g = numbers() print("made") print(next(g))What happens to a generator's local variables at a
yield?- They are kept, ready for the next next()
- They are deleted, like after return
- They are reset to 0
What does this print?
def double_up(items): for x in items: yield x * 2 g = double_up([1, 2, 3]) print(list(g)) print(list(g))Which line has a mistake? (The function should give every number from 1 to n.)
def one_to(n): for i in range(1, n + 1): return i print(list(one_to(3)))
Coding tasks
Write a generator
countdown(n)that yields n, n-1, … down to 1.Write a generator
evens_up_to(n)that yields the even numbers from 0 up to and including n.Write a generator
chapters(titles)that yields"Chapter 1: <title>","Chapter 2: <title>"and so on, one per title.