I was playing around with lists and functions on python and was trying to create a list of functions using a loop as following:
n = 5
fun = []
for i in range(n):
def f(x):
return x + i
fun.append(f)
I tried to test the list using prints as following
for s in range(n):
print(fun[s](1))
I expected to obtain 1 2 3 4 5 but instead got 5 5 5 5 5. When using the variable i
for i in range(n):
print(fun[i](1))
I obtained what I was expecting, however the all functions inside the list 'fun' behave like x + 4. I was wondering what is causing this issue and what can be done to fix it. Thank you.