Storing Lambdas in Dictionary

  closures, lambda, python

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?

Source: Python Questions

LEAVE A COMMENT