Search code examples
pythongeneratoryield

where does the yield store value in python


I understand generator generates value once at a time, which could save a lot memory and not like list which stores all value in memory.

I want to know in python, how yield knows which value should be returned during the iteration without storing all data at once in memory?

In my understanding, if i want to print 1 to 100 using yield, it is necessary that yield needs to know or store 1 to 100 first and then move point one by one to return value ?

If not, then how yield return value once at a time, but without storing all value in memory?


Solution

  • Simply put, yield delays the execution but remembers where it left off. However, more specifically, when yield is called, the variables in the state of the generator function are saved in a "frozen" state. When yield is called again, the built in next function sends back the data in line to be transmitted. If there is no more data to be yielded (hence a StopIteration is raised), the generator data stored in its "frozen" state is discarded.