yield

In Python, the yield keyword turns a function into a generator function, which returns an iterator that generates values on demand rather than generating them all at once. Using yield enables the function to maintain its state between calls, allowing you to iterate over data efficiently without the overhead of creating and storing the entire dataset in memory.

Python yield Keyword Examples

Here’s an example of how to use the yield keyword in a generator function:

Python
>>> def count_up_to(max):
...     count = 1
...     while count <= max:
...         yield count
...         count += 1
...

>>> for count in count_up_to(3):
...     print(count)
...
1
2
3

In this example, count_up_to() is a generator function that that returns an iterator. This iterator yields numbers from 1 up to a given maximum. You can use this iterator in a for loop.

Tutorial

How to Use Generators and yield in Python

In this step-by-step tutorial, you'll learn about generators and yielding in Python. You'll create generator functions and generator expressions using multiple Python yield statements. You'll also learn how to build data pipelines that take advantage of these Pythonic tools.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader