Comment

Comment by ot

Very interesting, I've been bitten by the same problem with Python once (capturing the iteration variable in a closure). To make things even worse, in Python the behaviour is inconsistent between list comprehensions and generator comprehensions:

  In [10]: lambdas = [(lambda: i) for i in xrange(10)]
  In [11]: [f() for f in lambdas]
  Out[11]: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
  
  In [12]: lambdas_gen = ((lambda: i) for i in xrange(10))
  In [13]: [f() for f in lambdas_gen]
  Out[13]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The problem was not fixed even in Python 3. I don't know if there has been any discussion about it.
parent ot 15 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton