1

I want to iteratively create a list of functions, with my desired result being phi = [lambda x: x+1, lambda x: x+2, lambda x: x+3]. The code I have here creates the same function 3 times: phi = [lambda x: x+i, lambda x: x+i, lambda x: x+i], but I would like the functions to be independent of i. How can I 'hard-code' the value of i while looping?

Code I am using:

for i in range(3):
    phi.append(lambda x: x + i)

The reason I want to do it this way is because I want 3 functions, rather than 1 that depends on i.

Jackdaw
  • 67
  • 5
  • Question is bit self-contradictory > "How can I 'hard-code' the value of i" > "I want 3 functions, rather than 1 that depends on i" Can you please clarify? – kkgarg Jul 28 '21 at 19:34
  • My desired result is `phi = [lambda x: x+1, lambda x: x+2, lambda x: x+3]`, that is, `phi` is a list of 3 different functions that are independent of `i`. – Jackdaw Jul 28 '21 at 19:37
  • Yes, perfect! Thanks! Fixed with `for i in range(3): phi.append(lambda x, i=i: x + i)` – Jackdaw Jul 28 '21 at 19:44

0 Answers0