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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With