Incorrect scope of list comprehension variables

Chris Rebert clp2 at rebertia.com
Sat Apr 3 06:53:57 EDT 2010


On Sat, Apr 3, 2010 at 3:30 AM, Alain Ketterlin
<alain at dpt-info.u-strasbg.fr> wrote:
> 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?

Quoting http://docs.python.org/reference/expressions.html#id19 :

Footnotes
[1]	In Python 2.3 and later releases, a list comprehension “leaks” the
control variables of each 'for' it contains into the containing scope.
However, this behavior is deprecated, and relying on it will not work
in Python 3.0

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list