1

Your help will be seriously appreciated

def test(passed):
    print(passed)

variable = []
for i in range(10):
    variable.append(lambda: test(i))

variable[4]()

expected result >>> 3

actual result >>> 0
(same with any item in the "variable" list)

can someone please explain why and how (if possible) I can fix this?

Dan
  • 45,079
  • 17
  • 88
  • 157
  • Because python has lexically scoped closures. `i` refers to whatever `i` is referring to at the time that the function is created. Although in this case, it is going to do a global lookup, but anyway, the value of `i` when you *call* your functions is the value of `i` after the loop has ended... try re-assigning `i` and maybe it will make sense. See the linked duplicates for what you can do to avoid this (one approach is to create *another* enclosing scope, so `variable.append((lambda x: lambda: test(x))(i))` – juanpa.arrivillaga Jun 23 '20 at 12:07
  • From the duplicate answers, I think the cleanest solution is to use [`partial`](https://docs.python.org/3/library/functools.html#functools.partial) instead of lambda: `variable.append(partial(test, i))` – Dan Jun 23 '20 at 12:09
  • @Dan I usually prefer just defining an explicit factory, `def test_factory(x): return lambda: test(x)` then in the loop `variable.append(test_factory(i))`, but `partial` works just fine – juanpa.arrivillaga Jun 23 '20 at 12:11
  • Factory looks good too, I just don't like the double lambda from a a readbility point of view `variable.append((lambda x: lambda: test(x))(i))` – Dan Jun 23 '20 at 12:14

0 Answers0