The yield statement in Python is used within a function to create a generator. A generator is a special type of iterator that allows you to iterate through a sequence of values, producing them one at a time, only when requested. This is different from returning all values at once.
Basics of yield
When a function includes the yield statement, it becomes a generator function. Calling this function does not execute its code immediately. Instead, it returns a generator object. You can then use the next() function on this generator to get the next value produced by the generator.
Example 1: Fixed Result Generator
Here’s a simple generator function that yields the same string every time:
def my_generator(): """Generator function that yields the same string when 'next' is called""" yield "More research is needed…" def main(): # Use the generator and obtain its next value print("I saved a bunch on the latest A.I.") print("Unfortunately, all it replies with is", next(my_generator())) print(next(my_generator())) print(next(my_generator())) print() if __name__=="__main__": main() |
Output:
I saved a bunch on the latest A.I. Unfortunately, all it replies with is More research is needed... More research is needed... More research is needed... |
In this example, each call to next(myGenerator()) creates a new generator and yields "More research is needed…".
Example 2: Collection Generator
A more practical example of a generator function yields successive elements from a collection:
def my_generator2(my_aliaslist): """Generator function that yields the same string when 'next' is called""" yield from my_aliaslist def main(): alias_list = ["monty", "python", "lamer"] it = my_generator2(alias_list) print("So, what do you call yourself?") print(next(it), "?") print(next(it), "?") print(next(it), "?") if __name__=="__main__": main() |
Output:
So, what do you call yourself? |
In this example:
- The my_generator2 function takes a list (my_aliaslist) and yields each element one at a time.
- yield from my_aliaslist is a shorthand for yielding each element in my_aliaslist.
Key Points of yield
- State Retention: Generators retain their state between calls. This means they remember where they left off in the iteration process.
- Lazy Evaluation: Generators produce items only when requested, which is useful for handling large datasets efficiently.
- Simplified Code: Using yield can make code more readable and maintainable compared to manually managing an iterator.