I am learning lambdas in Python. I need to create a list of functions f = [f1, f2...]
such that each function fi(x)
takes in a list x
and returns (x[i]-1)
.
This is how I tried coding it, but I am getting surprising results. Please help me understand why each of the three prints give different results. The last two have left me absolutely stumped!
f = [(lambda x: x[i]-1) for i in range(5)]
# I expect f to be [ (lambda x: x[0]-1), (lambda x: x[1]-1), ...]
x = [1, 2, 3, 4, 5]
print f[0](x), f[1](x), f[2](x) # output: 4 4 4 !!
print [f[i](x) for i in range(5)] # output: [0, 1, 2, 3, 4] as expected
print [f[k](x) for k in range(5)] # output: [4, 4, 4, 4, 4] wha?!!!
Edit: This question is quite different from the suggested duplicate. In the linked question there was a simple error where the user created a list of functions, instead of function-calls. However the answer by Tomasz Gandor discusses the same issue as asked here using several examples.