Dima Lituiev Dima Lituiev - 4 months ago 9
Python Question

list of lambdas in python

I have seen this question, but i still cannot get why such simple example does not work:

mylist = ["alice", "bob", "greta"]
funcdict = dict(((y, lambda x: x==str(y)) for y in mylist))
funcdict['alice']("greta")
#True
funcdict['alice']("alice")
#False
funcdict['greta']("greta")
#True


How is it different from:

[(y, y) for y in mylist]


Why
y
is not evalueated within each step of iteration?

Answer

The y in the body of the lambda expression is just a name, unrelated to the y you use to iterate over mylist. As a free variable, a value of y is not found until you actually call the function, at which time it uses whatever value for y is in the calling scope.

To actually force y to have a value at definition time, you need to make it local to the body via an argument:

dict((y, lambda x, y=z: x == str(y)) for z in mylist)