Hacker News new | ask | show | jobs
by obfuscate 5260 days ago
The inconsistency is because, in the generator-expression case, the calls to f() are being interleaved with the iterations of the generator (so the closed-over variable has the 'correct' value when f() is called). If you change this by running the generator to completion first, the behavior is the same as the list case:

  In [1]: lambdas_listgen = list(((lambda: i) for i in range(10)))
  In [2]: [f() for f in lambdas_listgen]
  Out[2]: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
1 comments

It's still really complicated semantics.
it's only complicated if you expect something which isn't there. it's a gotchya, true.
It's simple semantics with confusing behavior.