Generator expressions vs. comprehensions

Ian Kelly ian.g.kelly at gmail.com
Mon May 24 18:31:13 EDT 2010


Hi all,

I just ran into an interesting but rather subtle little wart today.
The following expressions are not functionally equivalent, even in
Python 3:

tuple(iterator.next() for i in xrange(n))

tuple([iterator.next() for i in xrange(n)])

In the first case, if iterator.next() raises a StopIteration, the
exception is swallowed by the generator expression.  The expression
evaluates to a truncated tuple, and the StopIteration is not
propagated.

In the second case, the StopIteration exception is propagated as
expected by the list comprehension.  Set and dict comprehensions also
behave this way in Python 3.

Is this distinction generally known?  The generator expression
behavior is understandable since a generator would do the same thing,
but I'm disappointed that the inconsistency exists and wasn't fixed in
Python 3 when we had the chance.

Cheers,
Ian



More information about the Python-list mailing list