Dima Lituiev Dima Lituiev - 3 months ago 7x
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))

How is it different from:

[(y, y) for y in mylist]

is not evalueated within each step of iteration?


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)