0

# What is the difference between return and yield

19th Jun 2019, 10:03 PM
8 Antworten
+ 7
River Your analogy reminds me of the Little Man Computer (LMC) for some reason. 😂👌 - Not that LMC is related to yield vs return. 😉 Micheal Shenouda Gad While the analogy is helpful for understanding this from 50,000 feet, the more technical explanation requires an understanding of python iterables and generators, which might sound more complex than they really are. Here are some references to understand these better: https://realpython.com/introduction-to-python-generators/ https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/ In the meantime, I'll expand on River's explanation by pointing out that yield is essentially a pause button for a function. The 1st time a function is called, the code runs until it hits a yield statement. The yield statement saves the local state and returns a value. The next time the function is called, the code resumes where it left off and runs until it hits the next yield or reaches the end of the function. I hope this helps as well.
20th Jun 2019, 5:51 AM
David Carroll
+ 7
I'm not great at Python, but here is a basic answer. Return is where it exits from a function with a value, but the local values within is destroyed. Yield is sort of exiting from a function but it remembers the state you had when you exited. If you were to do a 'next' from your 'main' you would be starting from the point you yielded from. Hope this helps!
19th Jun 2019, 10:30 PM
River
+ 7
Best I can. Imagine a function to be a room. Now imagine you entered that room and incremented a counter which had been initialised to 0. The value of this counter is 1. Now you return to the spot you were before you entered the room(your main). If you were asked to back in the room, the value of the counter would depend on how you had exited. If you had 'returned' from the room, the counter value would be 0. If you had yielded, the value would be 1. Hope this helps!
19th Jun 2019, 11:25 PM
River
+ 1
Thanks But can you tell me more because I didn't understand
19th Jun 2019, 11:12 PM
+ 1
Thanks River
20th Jun 2019, 12:06 AM