Module 13 · Lesson 03
Generator Functions and yield
Write generators with full function bodies: how yield pauses and resumes, keeping state between items, endless generators, yield from, and pipelines of small generator functions.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Pause and resume with yield
- Keep a running total
- Endless generators, safely
- Watch a countdown run
Functions that pause
Put `yield` in a function and it hands out values one at a time, pausing between them.
yield
yield valuehands out one value and pauses the function right there.Pause and resume
Each
next()carries on from the lastyielduntil it reaches the next one.State stays
Local names keep their values between items, so a running total just works.
yield from
yield from otherhands out every item of another iterable in turn.
Generators everywhere
Anything that produces a stream of values can be a generator.
- PagingFetch search results page by page and hand out each one as it arrives.
- Chart coloursAn endless generator gives the next colour for each new chart line.
- Folder walksYield every file in a folder tree, however deep it goes.
- SensorsYield a reading each time one comes in, for as long as the device runs.
Calling a generator function
This line looks like an ordinary call, but nothing in the function runs yet. Tap each part to see its job.
Part 1 of 3
generator object:What the call gives back: an iterator, ready to run the body a bit at a time.
Write functions that yield
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Pause and resume
Each next() runs the body only as far as the next yield.
Your turn: Add a third step that yields "poured", then ask for it.
def kettle():
print(" filling")
yield "full"
print(" heating")
yield "hot"
k = kettle()
print("kettle ready")
print(next(k))
print(next(k))Press Run to see what it prints.Watch a countdown pause and resume
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- def countdown(n):
- while n > 0:
- yield n
- n -= 1
- gen = countdown(2)
- print(next(gen))
- print(next(gen))
- print(next(gen, "lift off"))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.What type does the call give?
def g():
yield 1
print(type(g()).__name__)0 of 6 answered
Common generator misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
def gen(items): # any yield makes it a generator function
for x in items:
yield x * 2 # hand out a value and pause
g = gen([1, 2]) # nothing runs yet
next(g) # runs to the first yield: 2
list(g) # the rest: [4]
def forever():
n = 0
while True: # safe: runs only when asked
yield n
n += 1
def flatten(groups):
for group in groups:
yield from group # every item of group
return # inside a generator: stop earlyPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Fibonacci numbers, as many as you want
Write an endless generator of Fibonacci numbers (each is the sum of the two before it). Print the first eight, then the first one above 1000.
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
first_eight = []
for n in fibonacci():
if len(first_eight) == 8:
break
first_eight.append(n)
print(first_eight)
for n in fibonacci():
if n > 1000:
print("First above 1000:", n)
breakPress Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Expecting the body to run when the function is called
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
def report():
print('report started')
yield 'done'
report()Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Data engineering
Loading records into a database in batches
A nightly job copies customer sign-ups into a reporting database. Inserting one row at a time is slow, and loading the whole export at once could exhaust memory, so the job streams the records and groups them into batches of three for each insert.
Why Python fits
recordstakes the header withnext()and turns each later line into a dictionary.validdrops rows without an email and normalises the rest.batcheskeeps a list between items and yields it whenever it is full, plus whatever is left at the end. Only one batch is ever in memory, however large the export is.Pythonexport = """id,email 1,ana@example.com 2,BEN@EXAMPLE.COM 3, 4,cara@example.com 5,dev@example.com 6,eli@example.com 7,fay@example.com""" def records(text): lines = iter(text.splitlines()) header = next(lines).split(",") for line in lines: yield dict(zip(header, line.split(","))) def valid(rows): for row in rows: if row["email"]: row["email"] = row["email"].lower() yield row def batches(rows, size): batch = [] for row in rows: batch.append(row) if len(batch) == size: yield batch batch = [] if batch: yield batch for batch in batches(valid(records(export)), 3): print("INSERT", [row["id"] for row in batch])OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Can a generator yield in more than one place?
How do I know a function is a generator just by reading it?
What is the send() method I have seen on generators?
When should I still return a list?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 15 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.