[Tutor] "Strange" behaviour of list comprehension

eryksun eryksun at gmail.com
Wed Feb 13 23:16:20 CET 2013

On Wed, Feb 13, 2013 at 9:17 AM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> To be more precise, the comma at the end is part of a tuple (you can omit
> parentheses of a tuple in many cases). This makes the final for loop iterate
> over the tuple (range(y, 10), x + y == z). You'll notice that this only
> works if the variable 'z' is already defined, since the tuple isn't
> constructed in the for loop.

In 3.x the parser requires the parentheses in a list comprehension,
but not in a for loop. And the list comprehension is compiled as a
function, so you get an UnboundLocalError when trying to evaluate

Just for fun, here's an example that makes a function from the code of
a list comprehension in 3.x. The function takes the first iterator in
the comprehension as an argument:

    >>> f = lambda: [(x,y) for x in 'ab' for y in 'cd']
    >>> lcomp = type(f)(f.__code__.co_consts[1], globals())

    >>> lcomp(iter('12'))
    [('1', 'c'), ('1', 'd'), ('2', 'c'), ('2', 'd')]

Never do this. The code assumes the argument is an iterator, so it's
easy to trigger a segfault:

    >>> lcomp('12')
    Segmentation fault

More information about the Tutor mailing list