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.
Syntax
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)
Output:
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 statementfor
.
def simpleGeneratorFun(): for i in range (1, 4): yield i for value in simpleGeneratorFun(): print(value)
Output:
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
Output:
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 next()
statement.
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 statementnext()
.
4. Finding Sum of all generated values:
You can simply make the sum of all the values returned from generator function using the inbuiltsum()
function.
def simpleGeneratorFun(): n =3 for i in range (1, 4): yield i print "Sum of Series: ", sum(simpleGeneratorFun())
Output:
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)
Output:
1 1 2 3 5
Python yield vs return statement:
What is the difference between yield
and 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
Happy Pythoning!
Comments
Nur Amin Aifat
What kind of state have yield and why any state haven’t return statement?
explain it again please… just state.
Aniruddha Chaudhari
Nur,
In case of return and normal function, every time when you call function, it executes the complete code inside the function.
Whereas, in yield statement and generator, when you call the generator function, it executes the code inside the generator function from where it is left (does not execute the code complete). It saves the state.
Check the Python program- 1. Generating Number Series:
Nur Amin Aifat
What is the meaning of, generates the values on the fly?
Aniruddha Chaudhari
It means it does not save any values. And each value is generated every time when it is needed.
Avira
Thanks for sharing and detail about this Python topic.
Aniruddha Chaudhari
You’re welcome, Avira!
Fernando
The best explanation that I have found. Thanks for taking the time to teach others.
Aniruddha Chaudhari
Thanks, Fernando! And you’re welcome!