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,232
  • 18
  • 23
  • 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

0 Answers0