The python yield statement is used in a function to return the generator object. Using yield instead of returning the function instead of returning the output, it returns a generator that can be iterated upon.
You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.
Example yield statement in Python
In simple example code, the yield enables the function to remember its ‘state’, this function can be used to generate values in a logic defined by you. So, its function becomes a ‘generator’.
Generator to print even numbers.
def print_even(lst):
for i in lst:
if i % 2 == 0:
yield i
lst = [1, 4, 5, 6, 8]
for j in print_even(lst):
print(j, end=" ")
Output:
Difference between yield and return
Return | Yield |
---|---|
Returns the result to the caller | Used to convert a function to a generator. Suspends the function preserving its state |
Destroys the variables once execution is complete | Yield does not destroy the function’s local variables. Preserves the state. |
There is usually one return statement per function | There can be one or more yield statements, which is quite common. |
If you execute a function again it starts from the beginning | The execution begins from where it was previously paused |
Do comment if you have any doubts or suggestions on this Python yield tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.