python, generators, and yield

20 Aug 2008

Does anyone else think the python documentation is oddly organized? My search for "python generators yield" kinda sucked, here's my take.

A basic for loop:

for i in xrange(10):   # or range(10)
    print i

could be rewritten with generators as:

def myrange(maxi):
    i = 0
    while i < maxi:
        yield i
        i += 1

for i in myrange(10):
       print i

A function is a a generator if and only if it has a yield statement in it. You don't need to do anything else except use yield

A generator also automagically creates an iterator too. You can also iterate manually using next() and catch the StopIteration exception.

z = myrange(10)
    while True:
    except StopIteration:

Now you know just about everything you need to know about generators. Looking for more? Here's the tutorial section, notes on yield, and the Official Spec