Something is rotten in Denmark...

Ian Kelly ian.g.kelly at gmail.com
Tue May 31 17:47:33 EDT 2011


On Tue, May 31, 2011 at 3:14 PM, Martin Manns <mmanns at gmx.net> wrote:
> $ python
> Python 2.6.6 (r266:84292, Apr 20 2011, 11:58:30)
> [GCC 4.5.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> fs=[]
>>>> fs = [(lambda n: i + n) for i in range(10)]
>>>> [fs[i](1) for i in range(10)]
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This works by accident.

>>> [fs[i](1) for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [fs[0](1) for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [f(1) for f in fs]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

The i variable is part of the global scope, and as you iterate over
range(10) again it coincidentally takes on the same values as in the
original list comprehension.  You don't see this in Python 3 because
the scope of i is limited to the list comprehension, not global.

Cheers,
Ian



More information about the Python-list mailing list