Alex Rivera | Logout

Python: generator expression vs. yield

Asked 2010-01-03T16:09:26.717
99

In Python, is there any difference between creating a generator object through a generator expression versus using the yield statement?

Using yield:

def Generator(x, y):
    for i in xrange(x):
        for j in xrange(y):
            yield(i, j)

Using generator expression:

def Generator(x, y):
    return ((i, j) for i in xrange(x) for j in xrange(y))

Both functions return generator objects, which produce tuples, e.g. (0,0), (0,1) etc.

Any advantages of one or the other? Thoughts?

Edit
Report

1 Answer

19

There is no difference for the kind of simple loops that you can fit into a generator expression. However yield can be used to create generators that do much more complex processing. Here is a simple example for generating the fibonacci sequence:

>>> def fibgen():
...    a = b = 1
...    while True:
...        yield a
...        a, b = b, a+b

>>> list(itertools.takewhile((lambda x: x<100), fibgen()))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
answered 2010-01-03T16:30:39.633

Your Answer