2

I want to create a list of sine functions using a for loop where the parameters depend on a list. As a minimum working example, let us say that my list is

lst = [0, 50, 75, 83, 98, 84, 32]

I want my loop to output the following list of functions:

[0, sin(50x), sin(75x), sin(83x), sin(98x), sin(84x), sin(32x)]

Here's what I tried:

function = [];
lst = [0, 50, 75, 83, 98, 84, 32]
for m in lst:
    function.append(lambda x : np.sin(m*x))

This does give me a list of 7 functions:

[<function __main__.<lambda>(x)>,
 <function __main__.<lambda>(x)>,
 <function __main__.<lambda>(x)>,
 <function __main__.<lambda>(x)>,
 <function __main__.<lambda>(x)>,
 <function __main__.<lambda>(x)>,
 <function __main__.<lambda>(x)>]

But when I evaluate function[0](1) it outputs 0.5514266812416906 whereas it should be 0 (m=0 implies sin(0*x) = sin(0) = 0 for all values of x), so I am doing something wrong.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Amelia
  • 97
  • 8
  • 2
    This is one of the trickiest Python traps. Your lambdas are capturing the NAME `m`, not the value. When the loop ends, `m` is 32, so all the functions will use 32. The trick is to capture the value as a default: `lambda x, m=m: np.sin(m*x)`. – Tim Roberts Nov 16 '22 at 21:14
  • 1
    @TimRoberts: this is not only tricky in Python, it's also tricky in C# for similar reason. – Thomas Weller Nov 16 '22 at 21:15
  • 1
    `for i in range(len(lst)): function.append(lambda x, m=lst[i]: np.sin(m * x))` – Faisal Nazik Nov 16 '22 at 21:18

0 Answers0