Generator functions

Yield one result at a time

Lesson 15 of 20 · 12 min · Module 5: A more expressive Python toolkit

A generator describes a sequence without constructing its entire output list at once. It pauses each time it yields a value.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Distinguish yielding from returning
  • Understand generator consumption

The idea

A function containing yield returns a generator iterator. Iteration resumes the function until another yield or the end. Once exhausted, that iterator does not restart.

def first_three():
    for number in range(1, 4):
        yield number

print(list(first_three()))

01Create the generator

Calling the function creates an iterator. Its body starts running when an iteration operation requests a value.

02Pause at each match

yield sends one matching name to the caller and saves the function’s place. The next request resumes after that yield.

03Decide whether to materialize

list(generator) consumes all remaining values into a list. This is useful for display and tests, but a loop can process results directly.

Your turn

Write generator function passing_names(records). Yield each name whose numeric score is at least 70, preserving input order. An empty input yields no names. Use yield rather than returning a prepared list.

What the checks look for

  • Yields matching names in original order
  • Returns an iterator, not a list
  • An exhausted generator stays exhausted
Try it in the editor →

Take this with you

A generator separates a sequence’s recipe from the act of consuming it.

Go a little further

Write a second generator that yields running totals without storing all previous totals.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →