List comprehension + lambdas - strange behaviour

Neil Cerutti neilc at norwich.edu
Fri May 7 08:31:33 EDT 2010


On 2010-05-07, Terry Reedy <tjreedy at udel.edu> wrote:
> On 5/6/2010 3:34 PM, Artur Siekielski wrote:
>> Hello.
>> I found this strange behaviour of lambdas, closures and list
>> comprehensions:
>>
>>>>> funs = [lambda: x for x in range(5)]
>>>>> [f() for f in funs]
>> [4, 4, 4, 4, 4]
>
> You succumbed to lambda hypnosis, a common malady ;-). The
> above will not work in 3.x, which does not leak comprehension
> iteration variables.

It functions the same in 3.1.

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> funs = [lambda: x for x in range(5)]
>>> [f() for f in funs]
[4, 4, 4, 4, 4]

-- 
Neil Cerutti
*** Your child was bitten by a Bat-Lizard. ***



More information about the Python-list mailing list