When to use yield instead of return in Python

by Alex
When to use yield instead of return in Python

The yield statement pauses the function and returns the specified value back to the caller, saving the state so that the function can resume execution from where it left off. When such a function is called again, it will continue to execute from the instructions that follow it. This behavior allows the code to generate individual values as needed instead of computing all at once, e.g., by returning a list. Let’s take a look at the following snippet:
# A simple Python program to demonstrate
# a simple Python program to demonstrate how the yield
# A generator function that gives out 2 on
# on the first call, 4 on the second call, and
# 8 for the third
def simple_generator():
yield 2
yield 4
yield 8
# code to test simple_generator()
for value in simple_generator():
print(value)
Output:
2
4
8
A function with return sends the specified value back to the code that called it, while yield can create a sequence of return values. We should use yield when we want to handle many objects but don't want to store them all in memory. Yield is used in Python generators. Such a generator is defined as a regular function, but whenever it needs to output a value, it does so with the yield keyword rather than return. If the body of def contains yield, the function automatically becomes a generator.
# A Python program to generate powers of 2
# from 2 to 256
def get_next_num():
n = 2
# infinite loop to generate powers of 2
while True:
yield n
n *= 2 # If the next call to
# get_next_num() the execution
# will continue from here
# code to check get_next_num()
for num in get_next_num():
if num > 256:
break
print(num)
Output:
2
4
8
16
32
64
128
256

Related Posts

LEAVE A COMMENT