Incorrect scope of list comprehension variables

Raymond Hettinger python at rcn.com
Fri Apr 16 21:03:28 CEST 2010


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

It is the intended behavior in 2.x.  The theory was that a list
comprehension would have the same effect as if it had been unrolled
into a regular for-loop.

In 3.x, Guido changed his mind and the induction variable is hidden.
The theory is that some folks (like you) expect the variable to be
private and that is what we already do with generator expressions.

There's no RightAnswer(tm), just our best guess as to what is the most
useful behavior for the most number of people.

Raymond



More information about the Python-list mailing list