[Tutor] List comprehension + lambdas - strange behaviour
Alan Gauld
alan.gauld at btinternet.com
Thu May 6 23:15:34 CEST 2010
>> 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]
>>
>> Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The
>> 'x' was bound to the final value of 'range(5)' expression for ALL
>> defined functions. Can you explain this? Is this only counterintuitive
>> example or an error in CPython?
As others have pointed out you are returning a reference not a value.
You can do what you want by defining a lo cal closure using:
funs = [lambda y = x: y for x in range(5)]
Now you can do
for f in funs:
print f()
and get the answer you expect.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list