0

I have a function foo that takes 2 arguments a and b. I want to create a list of functions that are similar to foo, but value of a is fixed.

def foo(a,b): 
   return a*b

fooList = []
for i in range(n):
   fooList.append(foo(i))

I want fooList[i] to return a function that is similar to foo(i, b).

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
2ank3th
  • 2,610
  • 1
  • 18
  • 34

1 Answers1

1

You can use functools.partial:

from functools import partial

def foo(a, b):
    return a * b

fooList = []
for i in range(n):
   fooList.append(partial(foo, i))

Then you'd do fooList[i](5) to calculate i * 5.


You can also curry lambda functions, somewhat like this:

for i in range(n):
    fooList.append((lambda x: lambda y: x * y)(i))

You can then call that the same way as above.

cs95
  • 330,695
  • 80
  • 606
  • 657