I would like to create a list of function using list comprehension/for loop
def multiplier():
return [(lambda x: x*0),(lambda x: x*1),(lambda x: x*2),(lambda x: x*3)]
such that
[m(2) for m in multiplier()]
[m(3) for m in multiplier()]
will output [0,2,4,6] and [0,3,6,9] respectively
however when I attempt to do so:
def multiplier():
return [lambda x:i*x for i in range(4)]
or
def multiplier():
result = []
for i in range(4):
result.append(lambda x:x*i)
return result
or
def multiplier():
result = []
for i in range(4):
def m(x): return x*i
result.append(m)
return result
The following:
[m(2) for m in multiplier()]
[m(3) for m in multiplier()]
will output [6,6,6,6] and [9,9,9,9] respectively.
How do I create this list of functions without manually typing one by one! Any explanation? Thanks!