I'm trying to build a list of functions [f1(), f2(), ..., fn()] defined by the same function but with different arguments. For example, let say f(x,i) and the goal is to define the list [f1(), f2(), ..., fn()] where fi(x) = f(x,i).
I've already tried on Python 3 the code below:
F=[]
for i in range(5):
f = lambda x:x+i
F.append(f)
or
G=[0]*5
for i in range(5):
G[i]=lambda x:x+i
And then, by printing these built functions with x=0
print([F[i](0) for i in range(5)])
print([G[i](0) for i in range(5)])
But I get [4,4,4,4,4]
instead of [0,1,2,3,4]
.
From what I understand, the way I'm trying to build the list is wrong because the change of the i
value impacts all functions previously defined. So, how to avoid it?
Thank you!