1

The following code snippet which I came across, has output as 6,6,6,6

def multipliers():
    return [lambda x : i * x for i in range(4)]

print([m(2) for m in multipliers()])

I don't understand why the output is 6,6,6,6 instead of 0,2,4,6 ?

Can anyone please help me understand the internals of the above code as I am very new to Python. Thanks.

Matthew
  • 315
  • 3
  • 5
  • 16
  • 1
    While the duplicate is accurate, I'm sure there is a better duplicate - will update when I find it, you can also read the documentation: https://docs.python-guide.org/writing/gotchas/#late-binding-closures – AChampion Aug 26 '18 at 20:29
  • 1
    Also: https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result – AChampion Aug 26 '18 at 20:36
  • @AChampion we have a few clear canonicals for this problem now (depending on how the question is phrased). – Karl Knechtel Aug 16 '22 at 01:14

0 Answers0