List comprehension + lambdas - strange behaviour

Terry Reedy tjreedy at udel.edu
Thu May 6 21:49:07 EDT 2010


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 is equivalent to

funs = [lambda: x for y in range(5)]
del y # only for 2.x. y is already gone in 3.x
x = 4
[f() for f in funs]

Now, I am sure, you would expect what you got.

and nearly equivalent to

def f(): return x
x=8
funs = [f for x in range(5)]
[f() for f in funs]

# [8,8,8,8,8] in 3.x

Ditto

Terry Jan Reedy






More information about the Python-list mailing list