[Tutor] List comprehension + lambdas - strange behaviour
Ricardo Aráoz
ricaraoz at gmail.com
Thu May 6 21:53:07 CEST 2010
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]
>
> 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?
>
>
> Regards,
> Artur
>
Check this :
>>> funs = [(lambda: x) for x in range(5)]
>>> funs[0]()
4
>>> x
4
>>> x = 3
>>> funs[0]()
3
>>> del x
>>> funs[0]()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 1, in <lambda>
NameError: global name 'x' is not defined
So you see, your functions just return the value of x. That's because
the lambda have no parameter, so x refers to the global name x.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100506/f20eef54/attachment.html>
More information about the Tutor
mailing list