Problem: When to Prefer Yield Over Return
Let’s check out when do we prefer Yield over Return in Python. The former is used by the generator function to create an iterator. And the latter is a general-purpose statement to return a value from a regular function.
The return is a control statement in Python which declares the end of a function execution by returning some value to its caller. At the same time, every function clears its local stack usage such as variables or its attributes.
Also, it does not maintain any state as the return call marks its execution as completed. Hence, any further instance of the same method starts from its very first line of code.
Related – 100 Python Interview Questions and Answers
Case I – Need an Iterator Not a Single Value
At times, we need a function to pause instead of merely returning a value instantly. Also, the requirement is to execute it on a recurring basis and resume execution from the point of pause.
The yield statement allows us to halt a function execution, return a value, and preserves the current state, which is enough for continuing from the same point later on further request.
# Python program to Illustrate Usage of Yield # gen_func() yields 1 in the first call # 2 in the second, and 3 during the third. def gen_func(): yield 1 yield 2 yield 3 # Test code to test our generator function for var in gen_func(): print(var)
The above code gives the following output upon execution.
1 2 3
Case II – Need to Generate a Large List
Let’s bring more clarity on using yield instead of return.
The return statement transfers the output (a sequence, a string or a number, etc.) of a function to its caller all in one go. On the contrary, a yield can send back a sequence of values, one at a time in a step by step manner.
We should prefer yield when we want to traverse a large sequence, but don’t want to keep it in memory.
Yield turns a function into a Python generator. It has a function-like syntax, but whenever it requires to generate a value, it calls yield instead of the return.
If a Python function definition includes a yield call, then it automatically transforms into a generator function.
# Python program to produce cubes from 1 # to 1000 using a generator function # Let's have a infinite generator function def nextCube(): ii = 1; # This loop runs endlessly while True: yield ii*ii*ii ii += 1 # Next execution resumes # from this point # Driver code to test our generator for var in nextCube(): if var > 1000: break print(var)
Executing the above code produces the following result.
1 8 27 64 125 216 343 512 729 1000
We hope that after reading this post, you are clear about when to prefer Yield over Return. However, to learn more Python stuff, do read our step by step Python tutorial.