Skip to content

Writing generator functions with yield in Python

Any function that contains the yield keyword is a generator function. Calling it doesn’t run the body; it returns a generator, an iterator that produces values one at a time as you ask for them.

That makes generators useful for large or infinite sequences: values are produced on demand instead of being built into a list and held in memory all at once.

def countdown(n):
while n > 0:
yield n
n -= 1

Each time execution reaches yield n, the function hands n back to the caller and pauses, keeping its local variables. When the next value is requested, it resumes on the line after the yield.

The usual way to consume a generator is a for loop:

for i in countdown(5):
print(i)

Output:

5
4
3
2
1

You can also pull values by hand with next(). When the function returns (here, when the while loop ends), the generator raises StopIteration, which is how a for loop knows to stop:

>>> gen = countdown(2)
>>> next(gen)
2
>>> next(gen)
1
>>> next(gen)
Traceback (most recent call last):
...
StopIteration

A generator can only be iterated once. After it is exhausted, call countdown(5) again to get a fresh one.

For simple cases you don’t need a function. A generator expression looks like a list comprehension with parentheses:

squares = (x * x for x in range(1_000_000))
print(sum(squares))

sum consumes the values one by one, so the million squares are never stored in a list.

yield from passes through every value from another iterable, which is handy when one generator builds on another:

def countdown_twice(n):
yield from countdown(n)
yield from countdown(n)
print(list(countdown_twice(2))) # [2, 1, 2, 1]

If you need to index into the results, take their len(), or loop over them more than once, a list is simpler. Generators pay off when the sequence is large, expensive to compute, or never-ending, such as reading a big file line by line or streaming records from an API.

Further reading: Generators in the Python functional programming HOWTO, and the yield expression reference.

© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)