Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
Andrew Warner Avatar asked Mar 01 '23 23:03

Andrew Warner


1 Answers

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
like image 184
martineau Avatar answered Mar 10 '23 20:03

martineau