-1

Let's say I want a family of functions f[0], f[1], ... f[9] such that f[y](x) = x + 2 * y.

To achieve this, I try the following list comprehension:

fs = [(lambda x : x + 2 * y) for y in range(10)]

However, this does not work at all. For example, fs[0](2) evaluates to 20, instead of the desired 4.

What is going on here? Is this some strange scoping issue?

I have also tried things like [(lambda x: x + 2 * y) for y in the list(range(10))] but none of this helps.

1 Answers1

-1

y may be the last value it was set to

Set it as a default argument to the lambda

[(lambda x, _y=y : x + 2 * _y) for y in range(10)]
ti7
  • 16,375
  • 6
  • 40
  • 68