Python yield vs return Explained in Detail with Examples
In the morning, I had a discussion with one of my colleagues and usually, it happens at coffee. And I asked him, “for my project, I need a function that returns series of numbers every time I make a call”.
And he suggested, “Why don’t you use
yield instead of the
return statement in generator function?”.
Just after the coffee, I started digging into it.
After having a good understanding, I thought of curating my search for Python yield vs return with detail examples. So that you can find complete detail in one post.
There is so much confusion about Python yield and return statement to bear.
Yield statement in the Python is used whenever you need to define generator function. You can not use yield statement outside of generator function.
When you use yield statement in any function, it turns it into a generator function.
def generatorFunction(): ---- yield <return_value>; ----
To understand the yield statement in Python, you should know the generator function.
So let’ see…
What is Generator in Python?
How is generator function is different from a normal function?
As per the name “Generator”, is a function that generates the values (more than one or series of values). It behaves like an iterator.
How does generator different from iterators?
You can call generator function in the loop.
Simply, when you write yield statement in any function, it becomes generator function.
Generator functions are special types of iterates that iterate only once. It does not save any values in memory. It generates the values on the fly.
How do yield Statement and Generator work in Python?
The syntax of yield statement is similar to return statement but behaves differently.
- Whenever yield statement occurs inside generator function, the program pauses the execution and return the value to the caller.
- It retains the state of the function where it is paused.
- Next time, when a caller calls the generator function, function body executes the statement from where it has been paused instead of executing the first statement.
- You can call the generator function as long as it has not reached its last statement.
I know it is little difficult to understand by just reading. Let’s dive in the example to clear your understanding.
Python yield Examples with Generator Function:
1. Generating Number Series:
def simpleGeneratorFun(): n =1 yield n n = n+1 yield n n=n+1 yield n for value in simpleGeneratorFun(): print(value)
1 2 3
In the above program, we are literally calling the function
simpleGeneratorFun() three times.
How does above code work?
- When you call function
simpleGeneratorFun()the first time, line number 2 and 3 are executed.
- When you call the same function second time, it executes line number 4 and 5.
- For the third call, it executes lines of code from line 6 and 7.
2. Calling Generator Function using For Statement:
Above program, you can just fold it by using statement
def simpleGeneratorFun(): for i in range (1, 4): yield i for value in simpleGeneratorFun(): print(value)
1 2 3
3. Using next Statement:
You can also use
next() statement for iteratively calling generator functions.
def simpleGeneratorFun(): for i in range (1, 4): yield i obj = simpleGeneratorFun() nValue = next(obj) print nValue nValue = next(obj) print nValue nValue = next(obj) print nValue
1 2 3
If you call
nValue = next(obj) one more time, it throws an exception as…
Traceback (most recent call last): File "yield.py", line 13, in <module> nValue = next(obj) StopIteration
There are some drawbacks using
next() over for loop.
You have to write
next() for each call to generator function. If there are a huge number of calls to the generator function, it is tedious to call each time to
The number of iteration required to complete execution of generator function is same as a number of yield statement into the generator function. If you are not aware of the number of yield statement in your function, it is convenient to use for loop instead of a statement
4. Finding Sum of all generated values:
You can simply make the sum of all the values returned from generator function using the inbuilt
def simpleGeneratorFun(): n =3 for i in range (1, 4): yield i print "Sum of Series: ", sum(simpleGeneratorFun())
Sum of Series: 6
5. Generating Fibonacci Series using yield Statement:
Take this real-time use of yield statement to generate Fibonacci series.
def simpleGeneratorFun(): pre1 = 1 pre2 = 1 sumValue = 1 yield sumValue for i in range (0, 5): yield sumValue sumValue = pre1 + pre2 pre1 = pre2 pre2 = sumValue for value in simpleGeneratorFun(): print(value)
1 1 2 3 5
Python yield vs return statement:
What is the difference between
return statement in Python?
- Return statement just returns the value to its caller. It does not preserve any state from last function call.
- Whatever you write after the return statement does not execute. So you have to write return statement usually at the end of the function.
- You can write yield functions anywhere in generator function. The code after the yield statement is executed in next function call.
- Return statement does not retain any state. Every time you call function, it executed independently.
- In yield, the function is executed from where it is paused in last function call.
When to use of Yield statement over return?
In Python, the return statement does not save any state and it simply returns value to the caller. When you need to produce a series of values for every time calling function, use yield statement.
Any point to discuss? Please let me know in the comment.
There are some related codes you can try running them.
- List and Tuple (Difference Between Two)
- Reverse String in Python using Extended Slice Syntax
- Get all the Permutations of String