When to Prefer Yield Over Return in Python

Let’s check out when do we prefer yield over return in Python.

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.

When to Prefer Yield Over Return

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

Some more facts on using Yield instead of Return

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 Python generators. 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