0

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!

sdenis
  • 1

1 Answers1

0

Use functools.partial:

from functools import partial

def foo(x, y):
    return x + y

funcs = [partial(foo, i) for i in range(10)]
for f in funcs:
    print(f(10))
Austin
  • 25,759
  • 4
  • 25
  • 48
Netwave
  • 40,134
  • 6
  • 50
  • 93