Incorrect scope of list comprehension variables

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Tue Apr 6 04:51:09 EDT 2010


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

>> d = dict()
>> for r in [1,2,3]:
>>     d[r] = [r for r in [4,5,6]]
>> print d
>
> This isn't directly relevant to your problem, but why use a list 
> comprehension in the first place? [r for r in [4,5,6]] is just [4,5,6], 
> only slower.

Sure. But I've actually spent some time reducing the real code to a
simple illustration of the problem.

>> THe problem is that the "r" in d[r] somehow captures the value of the
>> "r" in the list comprehension, and somehow kills the loop interator. The
>> (unexpected) result is {6: [4, 5, 6]}.
>
> Actually, no it doesn't kill the loop at all. You have misinterpreted 
> what you have seen:

It kills the iterator, not the loop. Sorry, I used 'kill' with the
meaning it has in compiler textbooks: to assign a new value to a
variable.

> It is expected, because list comprehensions leak the variable into the 
> enclosing scope.

Thanks.

-- Alain.



More information about the Python-list mailing list