1

I want to create a dictionary of lambda functions, something like this:

test = {"test_{}".format(i): lambda x : x + i for i in range(3)}

But when I try it out as follows:

print(test["test_0"] (0))
print(test["test_1"] (0))
print(test["test_2"] (0))

I get as a result:

2
2
2

Somehow all the lambdas are the same! What is going on and how do i fix it?

Jsevillamol
  • 2,425
  • 2
  • 23
  • 46
  • 1
    Try this: `test = {"test_{}".format(i): lambda x, i=i : x + i for i in range(3)}` – brandonwang Aug 11 '18 at 15:53
  • 1
    @Jsevillamol, just define a function that returns a lambda. `def create_lambda(i): return lambda x: x + i`. Then use it in your loop: `test = {"test_{}".format(i): create_lambda(i) for i in range(3)}`. Should get what you want. – Bruno Lubascher Aug 11 '18 at 18:20

0 Answers0