Generators in Python.

The following examples are using Python 2.x but now after seeing Python 3.x released I’m interested in generators larger role in Python. Generators remind me of accumulators: generators accumulate a comprehensive result that you can add to with calls to yield. Take the following as an example.

def cubes(c):
    for i in range(c):
        yield i ** 3

What this code does is pretty obvious, except the yield statement. What does the function return – a generator. The generator can be used like a java iterator, and you add items to this iterable object by calling yield in your generator function. It can be used in several ways, like the following.

for i in cubes(10):
    print i, ';',

Or

x = cubes(10)
print x.next()
print x.next()
print x.next()

Eventually, using this approach, an exception will be thrown when you’ve exhausted the generator.

If you still want to use the result of the generator as a list, you can still do this. Simply cast the result to a list.

x = list(cubes(10))
print x

That is all I have to say about generator functions for now. They’re really interesting and somewhat useful, however, I’m not quite sold on the conversion to them as Python 3.x seems to be pushing. What will happen in Python 4.x?

This entry was posted in Programming and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.