Incorrect scope of list comprehension variables

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Sat Apr 3 06:30:32 EDT 2010


Hi all,

I've just spent a few hours debugging code similar to this:

d = dict()
for r in [1,2,3]:
    d[r] = [r for r in [4,5,6]]
print d

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]}. Changing r to s inside the list
leads to the correct (imo) result.

Is this expected? Is this a known problem? Is it solved in newer
versions?

This is python 2.6.4, on a stock ubuntu 9.10 x86-64 linux box. Let me
know if more detail is needed. Thanks in advance.

-- Alain.



More information about the Python-list mailing list