Mark Borgerding mborgerding at cinci.rr.com
Sat Jan 17 20:27:19 CET 2004

km wrote:
> Hi all,
> i didnt understand the purpose of  'yield' keyword and the concept of 'generators' in python.  can someone explain me with a small example how  generators differ from normal function calls?
> kindly enlighten
> regards,
> KM

I think of it as an "interrupt" that provides a value back to the caller 
for each value in a sequence.  It can also be loosely thought of as an 
iterator(sort of).

Here's an example that may (or may not) help:

def foo():
     print 'entering foo function'
     for i in range(3):
         print 'yielding %s' % i
         yield i
     print 'leaving foo function'

for x in foo():
     print  'x is %s' % x

prints out the following:

entering foo function
yielding 0
x is 0
yielding 1
x is 1
yielding 2
x is 2
leaving foo function

More information about the Python-list mailing list