Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

IMO, the problem here is not the closure but how i is updated instead of being a new variable at each iteration. I guess it's like that for the sake of performance, but if i was immutable, that wouldn't happen. I.e. i would be a whole new variable at each iteration.

Here's another example:

  in: lambdas = [(lambda i: lambda: i)(i) for i in xrange(10)]
  in: [f() for f in lambdas]
  out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Why is it a different i? It's misleading because sometime we have a reference and sometime we've got a whole new variable.


Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: