yield
In Python, the yield keyword turns a function into a generator function, returning 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 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
Build generator functions and generator expressions with the Python yield statement, and learn when lazy evaluation pays off.
For additional information on related topics, take a look at the following resources:
- Python Generators 101 (Course)
- Python for Loops: The Pythonic Way (Tutorial)
- How to Use Generators and yield in Python (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.