0

I need a list of functions, such as:

flist = []
flist.append(lambda x : 2*x )
flist.append(lambda x : 4*x )
flist.append(lambda x : 6*x )
print flist[0](1), flist[1](1), flist[2](1)

This works and the output is 2 4 6, as expected. Now if I want to obtain this from a for loop:

flist = []
for n in range(3):
    flist.append(lambda x : 2*(n+1)*x)
print flist[0](1), flist[1](1), flist[2](1)

or using comprehension:

flist = []
flist = [lambda x : 2*(n+1)*x for n in range(3)]
print flist[0](1), flist[1](1), flist[2](1)

... I get 6 6 6 in both cases. Of course I could use a function such as f(x,n) instead of a list. The reason I need a list is for use in numpy.piecewise() or select() functions. Any explanation/advice?

poke
  • 369,085
  • 72
  • 557
  • 602
Jourdans
  • 53
  • 5
  • Welcome to stackoverflow. You should add your programming language to the list of tags (I guess it's python). – archz May 06 '15 at 09:00
  • Yes, I agree this was a duplicate and the previous answers solve my priblem. In the present notation, my favorite solution would be: – Jourdans May 08 '15 at 07:55

0 Answers0