I'm looking to generate a list of similar but different functions, within a for loop. A MWE (which doesn't achieve the goal) would be as follows:
def generic(a, n):
return a + n
def make_funs():
N = 5
functions_out = []
for n in range(N):
functions_out += [lambda x : generic(x, n)]
return functions_out
funs = make_funs
The goal would be that to get
funs[0]
> result = {function}
print(funs[0](1))
> 1
print(funs[2](1))
> 2
and so forth. The current code above returns 5
for any x
I put into print(funs[x](1))
, implying that all the functions in my funlist
are being created with n = 4
.
Note that this question is related to, yet meaningfully different from the question here. There, the lambda functions being creater only take one input variable, and so treats the x
as I need to treat the n
here. The desired output of that question is a list of numbers, my desired output is a list of functions.