The python yield statement is used in a function to return the generator object. Using yield instead of return the function instead of returning the output, it returns a generator that can be iterated upon.
Example yield statement in Python
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=" ")
Difference between yield and return
|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 and suggestions on this Python yield tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.