+ 6
What is main difference between return and yield statement?
5 Answers
+ 2
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.
+ 2
The function will only be called, when the generator value is used (converted to an iterable or iterated through).
Example:
def a():
print("Hello")
yield "Something"
b = a() #No output
list(b) #Output: Hello
for i in b: #Output Hello
pass
The thing that is cool with generators is when you use it in a for loop...
Example:
def c():
print("A")
yield 0
print("B")
yield 1
print("C")
yield 2
print("D")
for i in c():
print(i, "OK")
The function will in beginning be called normally, but when yield statement is used, the function call will be paused, it waits the loop to finish it's current iteration, when iteration ends, the function will continue until another yield statement will be used and same carousel will continue until either the loop is broken with break statement or function runs out of return values.
Output:
A
0 OK
B
1 OK
C
2 OK
D
+ 1
yield does not break the function call
yield changes function into a generator, which behaves little different than a normal function.
+ 1
Cbrâ[ Exams ] Actually it exists, but with different purpose
0
The yield statement suspends functionâs execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. Return sends a specified value back to its caller.