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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python "for" Loops (Definite Iteration) (Tutorial)
- Python Generators 101 (Course)
- How to Use Generators and yield in Python (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- The Python for Loop (Quiz)