List comprehension + lambdas - strange behaviour

Artur Siekielski artur.siekielski at gmail.com
Thu May 6 15:34:53 EDT 2010


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



More information about the Python-list mailing list