Say I want to get a list of functions that returns x * 0
, x * 1
, ..., x * 9
(x
is the input variable). I am using a lambda expression in a list comprehension. Below is my code with x = 1
:
x = 1
funcs = [lambda x: x * i for i in range(10)]
res = [f(x) for f in funcs]
print(res)
However, I am getting
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
The expected result should be
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
What is wrong with my code and how should I fix it?