Yield
Fredrik Lundh
fredrik at pythonware.com
Wed Nov 15 12:25:54 EST 2006
Mateuszk87 wrote:
> may someone explain "yield" function, please. how does it actually work
> and when do you use it?
it returns a value from a function without actually terminating the
function; when the function is resumed, it'll continue to execute after
the yield.
a function that contains a yield statement is called a "generator", and
is most often used in a for-in loop, or in other contexts that expect a
sequence. the loop is automatically terminated when the function
returns in a usual way:
>>> def gen():
... yield 1
... yield 2
... yield 3
...
>>> for item in gen():
... print item
...
1
2
3
>>> sum(gen())
6
>>> [str(i) for i in gen()]
['1', '2', '3']
you can also use the generator "by hand"; when you call a generator
function, it returns a special "generator object", and then immediately
suspends itself. to run the generator, call its "next" method:
>>> g = gen()
>>> g
<generator object at 0x00AE64E0>
>>> g.next()
1
>>> g.next()
2
>>> g.next()
3
when the generator is exhausted, it raises a StopIterator exception:
>>> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
reference information:
http://effbot.org/pyref/yield.htm
hope this helps!
</F>
More information about the Python-list
mailing list