2

I am getting the following results in Python3

>>> [f() for f in ((lambda: k) for k in range(5))]
[0, 1, 2, 3, 4]

This is what I would expect, however I when I use list comprehension instead, I get:

>>> [f() for f in [(lambda: k) for k in range(5)]]
[4, 4, 4, 4, 4]

Why is that the case? It's very unintuitive to me. I thought that perhaps the function gets somehow copied, but no:

>>> fs = [(lambda: k) for k in range(5)]
>>> fs[0] is fs[1]
False
user1747134
  • 2,374
  • 1
  • 19
  • 26
  • For more info http://stackoverflow.com/questions/34554717/weird-behaviour-in-python-with-dict-of-lambda-functions/34555043#34555043 – Mazdak Apr 11 '16 at 09:38
  • Very common Python mistake. Each call to the lambda returns the `k` object. By the time the range is finished, the `k` object has the value 4. – Tim Roberts Aug 18 '22 at 06:05

0 Answers0