Summary: In this tutorial, we will learn the significance of the yield statement in Python with the help of examples.
The yield statement in Python suspends the function execution and returns a value to the caller function.
By using it the function state remains preserved, so on another call, the function starts its execution from the point where its last execution was suspended.
Consider the following example of yield in python:
def myFunction():
print("First Hello")
yield 1
print("Second Hello")
yield 2
print("Third Hello")
for x in myFunction():
print(x)
myFunction() #no-output
Output:
First Hello 1 Second Hello 2 Third Hello
Simply calling the function (i.e myFunction()
) will not output any result because the yield statement makes a function a generator.
To understand what a generator is in Python, we need to know python iterable.
Iterable
When we want to read certain values multiple times we store it usually as a list.
myList = [1, 5, 9, 7]
for x in myList:
print(x)
Here myList is an Iterable. It is very useful when we want to read it multiple times.
But sometimes with large numbers of values, it becomes inefficient when it is only needed to be read once or hardly twice.
Here comes the python generator in rescue.
Generators
Generators are iterators, a kind of iterable you can only iterate over once.
They does not store all the values in memory, they generate the values on the fly.
A generator is created using () whereas a list is created using [].
Recommended: List Comprehension
myGenerator = (x*x for x in range(5))
print("First call")
for x in myGenerator:
print(x)
print("Second call")
for x in myGenerator:
print(x)
Output:
First call 0 1 4 9 16 Second call
Notice the second call does give any output because a generator can be used only once.
Yield
yield is like return but it makes the function return a generator instead of some value.
In the first example when we called myFunction() we didn’t get any output because myFunction() returns a generator, hence it needs to be iterated using for … in … in python.
To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky 🙂
myFunction() gets replaced by a generator and on each successive call code up to the next yield gets executed and the yield value is returned, unless there is no more return or yield in the function.
So the output which we got can be analyzed as:
First Hello ---> printed by the function/generator on first call 1 ---> print(x) in for loop Second Hello ---> printed by the function/generator on second call 2 ---> print(x) in for loop Third Hello ---> printed by the function/generator on third call
Hope you got some idea about yield in python. If you still have any doubts or suggestions then comment below.