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
  • 115,751
  • 26
  • 228
  • 437
2ank3th
  • 2,948
  • 2
  • 21
  • 35

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
  • 379,657
  • 97
  • 704
  • 746