When to use yield instead of return in Python?
Last Updated :
08 Sep, 2022
The yield statement suspends a function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.
Let’s see with an example:
Python
def simpleGeneratorFun():
yield 1
yield 2
yield 3
for value in simpleGeneratorFun():
print (value)
|
Output:
1
2
3
Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory. Yield is used in Python generators. A generator function is defined just like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
Python
def nextSquare():
i = 1
while True :
yield i * i
i + = 1
for num in nextSquare():
if num > 100 :
break
print (num)
|
Output:
1
4
9
16
25
36
49
64
81
100
Please Login to comment...