Skip to contentSkip to navigation

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 value hands out one value and pauses the function right there.

  • Pause and resume

    Each next() carries on from the last yield until it reaches the next one.

  • State stays

    Local names keep their values between items, so a running total just works.

  • yield from

    yield from other hands 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

Tap any part of the code below, or press Next.1 of 3 explored

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.

Python
def kettle():
    print("  filling")
    yield "full"
    print("  heating")
    yield "hot"

k = kettle()
print("kettle ready")
print(next(k))
print(next(k))
Output
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.

  1. def countdown(n):
  2. while n > 0:
  3. yield n
  4. n -= 1
  5. gen = countdown(2)
  6. print(next(gen))
  7. print(next(gen))
  8. 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 notesOpen

yield instead of return

A function that contains yield anywhere in its body is a generator function. Calling it does not run the body. It returns a generator object, an iterator that runs the body a bit at a time:

Try it 1: edit me, then Run
def three_steps():
    print("step one")
    yield 1
    print("step two")
    yield 2
    print("step three")

gen = three_steps()      # nothing printed yet
print(next(gen))         # step one, then 1
print(next(gen))         # step two, then 2
next(gen)                # step three, then StopIteration
Output
Press Run to see what it prints.

Each next() runs the body from where it last stopped until it reaches the next yield. The value after yield is what next() returns, and the function pauses right there. When the body reaches its end (or a return), the generator raises StopIteration, so for loops and list() stop cleanly.

State is kept between items

While a generator is paused, all its local variables stay alive. That is what makes it more powerful than a generator expression:

Try it 2: edit me, then Run
def running_total(numbers):
    total = 0
    for n in numbers:
        total += n
        yield total

print(list(running_total([5, 10, 3])))   # [5, 15, 18]
Output
Press Run to see what it prints.

total survives from one item to the next. Writing the same thing as an iterator class would need __init__, __iter__, __next__ and manual StopIteration; the generator needs five lines.

Compare it with a function that builds a list:

Try it 3: edit me, then Run
def running_total_list(numbers):
    result = []
    total = 0
    for n in numbers:
        total += n
        result.append(total)
    return result
Output
Press Run to see what it prints.

Both give the same items, but the list version finishes all the work and holds every result before the caller sees the first. The generator hands out each result as soon as it is ready and holds none of them.

Endless generators

Because a generator only works when asked, it can describe a sequence that never ends:

Try it 4: edit me, then Run
def ids(prefix):
    n = 1
    while True:
        yield f"{prefix}-{n:03}"
        n += 1

make_id = ids("ORD")
print(next(make_id))     # ORD-001
print(next(make_id))     # ORD-002
Output
Press Run to see what it prints.

while True is safe here, since the loop only advances when someone calls next(). What is not safe is asking for everything: list(ids("ORD")) never finishes. Consume endless generators with next(), with a for loop that has a break, or with itertools.islice(gen, 10), which takes the first ten items; the itertools lesson covers it.

return in a generator

A bare return inside a generator simply ends it early. A value after return is not handed to the loop; it is attached to the StopIteration and ignored by ordinary loops. So return results at the end of a generator does not give the caller a list; use yield for every value the caller should see.

yield from

yield from iterable hands out every item of another iterable, one by one, as if you had written a for loop with a yield inside:

Try it 5: edit me, then Run
def all_tasks(lists):
    for tasks in lists:
        yield from tasks

print(list(all_tasks([["wash"], ["shop", "cook"]])))
# ['wash', 'shop', 'cook']
Output
Press Run to see what it prints.

It is especially neat for recursive structures, where a generator calls itself:

Try it 6: edit me, then Run
def walk(folder, path=""):
    for name, content in folder.items():
        if isinstance(content, dict):
            yield from walk(content, path + name + "/")
        else:
            yield path + name
Output
Press Run to see what it prints.

Each level of the folder tree yields its files and passes through whatever the deeper levels yield.

Pipelines of generator functions

A powerful pattern is to give each step of a task its own small generator function, each taking an iterable and yielding results:

Try it 7: edit me, then Run
def read_lines(text):
    for line in text.splitlines():
        yield line.strip()

def skip_comments(lines):
    for line in lines:
        if line and not line.startswith("#"):
            yield line

def parse(lines):
    for line in lines:
        name, qty = line.split("=")
        yield name, int(qty)

config = "# stock\napples=4\n\npears=7"
for item in parse(skip_comments(read_lines(config))):
    print(item)
Output
Press Run to see what it prints.

Each function is short, easy to test on its own and reusable in other pipelines. Nothing runs until the final for loop pulls the first item through all three stages. Swap read_lines for a function that reads a real file and the rest does not change.

Generators are still one-shot

A generator object is an iterator, so it is used up after one pass, exactly like the generator expressions in the previous lesson. The generator function, however, can be called again to get a fresh generator: running_total(data) a second time starts from zero. That is why it is common to pass around the function or the original data and create the generator where it is consumed.

Syntax

The general shape of the statements in this lesson.

syntax.py
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 early
Output
Press 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

Beginner

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.

Python
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)
        break
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The generator keeps a and b between items, so each next() does one step of the sequence. Both loops stop with break, which is what makes the endless while True safe. Each loop calls fibonacci() again, so the second search starts from 0 with a fresh generator.

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.

Buggy code: run it
def report():
    print('report started')
    yield 'done'

report()
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints nothing at all

Write this instead

def report():
    print('report started')
    yield 'done'

for message in report():
    print(message)

Why it happens

Calling a generator function only creates the generator; the body runs when something asks for an item.

In the real world

Where this shows up in software people use every day.

  1. Loading records into a database in batches

    Data engineering

    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

    records takes the header with next() and turns each later line into a dictionary. valid drops rows without an email and normalises the rest. batches keeps 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.

    Python
    export = """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])
    Output
    Press 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?

Yes. A generator can have many yield statements, inside loops, branches or one after another. Execution simply pauses at whichever one it reaches next.

How do I know a function is a generator just by reading it?

Look for yield anywhere in its body. Even one yield inside an if that never runs makes the whole function a generator function.

What is the send() method I have seen on generators?

Generators can also receive values with gen.send(value), which becomes the result of the paused yield expression. It is used in advanced code such as coroutines; ordinary data processing only needs next() and for loops.

When should I still return a list?

When the caller needs the whole result at once, several times, or needs its length, a list is simpler. Generators shine for large or endless data and for pipelines where items are used once.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.