+ 6

What is main difference between return and yield statement?

10th Sep 2019, 5:41 PM
Harish Gajjar
Harish Gajjar - avatar
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.
10th Sep 2019, 5:57 PM
KfirWe
KfirWe - avatar
+ 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
10th Sep 2019, 6:12 PM
Seb TheS
Seb TheS - avatar
+ 1
yield does not break the function call yield changes function into a generator, which behaves little different than a normal function.
10th Sep 2019, 5:57 PM
Seb TheS
Seb TheS - avatar
+ 1
Cbr✔[ Exams ] Actually it exists, but with different purpose
10th Sep 2019, 7:15 PM
Seb TheS
Seb TheS - avatar
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.
11th Sep 2019, 2:12 PM
Preet Talajiya
Preet Talajiya - avatar