yield
Robert Brewer
fumanchu at amor.org
Sat Jan 17 15:01:48 EST 2004
Gerrit Holl wrote:
Gerrit Holl wrote:
> If a generator reaches a 'yield' statement, it returns
> the result of the expression behind the 'yield' statement.
> ...When you call the 'next' method of the generator, the
> body is executed, until it reaches a 'yield' statement.
> When you call the body again, it is executed again, until
> it reaches a 'yield' statement again,
A bit more explicitly (so as not to mislead the original poster):
When you call the body again, the function "picks up where it left off"
rather than "it is executed again". Example:
>>> def gen():
... x = 0
... while x < 5:
... yield x
... x += 1
...
>>> [a for a in gen()]
[0, 1, 2, 3, 4]
If it were "executed again", you'd be rebinding x to 0 each time, and
would never exit the while loop, nor would x be incremented. However,
since it "picks up where it left off" (i.e. the yield statement), x is
incremented and the while loop continues until x == 5.
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list