List comprehension + lambdas - strange behaviour
Emile van Sebille
emile at fenx.com
Thu May 6 16:26:44 EDT 2010
On 5/6/2010 12:34 PM Artur Siekielski said...
> Hello.
> I found this strange behaviour of lambdas, closures and list
> comprehensions:
>
>>>> funs = [lambda: x for x in range(5)]
funs is now a list of lambda functions that return 'x' (whatever it
currently is from whereever it's accessible when invoked)
>>> [f() for f,x in zip(funs,range(5))]
[0, 1, 2, 3, 4]
>>> del x
>>> [f() for f in funs]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in <lambda>
NameError: global name 'x' is not defined
>>>
Emile
More information about the Python-list
mailing list