Andrew Warner
Andrew Warner

Reputation: 53

Storing Lambdas in Dictionary

I am trying to store lambda functions in a python dictionary. It seems that the loop overwrites all of the data stored in the dictionary with the last lambda. For example:

example_dict = {}
for i in range(5):
    example_dict[i] = lambda x: x + i

for key, func in example_dict.items():
    print(key, func(10))

Should output

0 10
1 11
2 12
3 13
4 14

But the actual output is:

0 14
1 14
2 14
3 14
4 14

This is very interesting to me. Anybody know why the last lambda function overwrites all of the other data in the dictionary?

Upvotes: 4

Views: 182

Answers (1)

martineau
martineau

Reputation: 123491

It's not overwriting the last lambda, they all point to the final value of i in the for loop because of how closures work. You can avoid it by giving the lambda functions a default argument:

example_dict = {}

for i in range(5):
    example_dict[i] = lambda x, i=i: x + i

for key, func in example_dict.items():
    print(key, func(10))

Output with change:

0 10
1 11
2 12
3 13
4 14

Upvotes: 7

Related Questions