0

Consider the following piece of code, which creates a list of several functions:

func = lambda a,x: a*x

func_list = []
for i in range(3):
    __tmp = lambda x: (i+1)*x
    func_list.append(__tmp)

x = 2
print func_list[0](x)
print func_list[1](x)
print func_list[2](x)

The expected output is 2,4,6, however the actual output is 6,6,6. Somehow, the first and second elements of the list were changed to the value of the third element! I am not sure why this is happening? I've seen issues where people do something like list = [0]*4 in which all elements would refer to the same entity, but my case seems to be different.

space_voyager
  • 1,984
  • 3
  • 20
  • 31

0 Answers0