3 ms·
You're right, this is the same problem that Python has with closures, for example: >>> l = [] >>> for i in range(10): ... l.append(lambda: i)
by bakery2k 8y ago
You're right, this is the same problem that Python has with closures, for example:
>>> l = []
>>> for i in range(10):
... l.append(lambda: i)
...
>>> for j in range(10):
... print(l[j](), end=' ')
...
9 9 9 9 9 9 9 9 9 9
The issue isn't really closing over the variable instead of the value, but the fact that Python re-uses the same variable for each iteration of the loop. C# used to behave the same way, but its designers considered this bad enough that they made a breaking change to the language to fix it [1].
Unfortunately, C#'s solution (creating a new variable for each execution of the loop body) isn't really an option for Python. It would conflict with the rest of the language, which only uses variables scoped to whole functions.
Note that Go makes the same mistake as in earlier versions of C# [2].
[1] https://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ https://ericlippert.com/2009/11/12/closing-over-the-loop-var...
[2] https://play.golang.org/p/Pt6BN2Mj-WL https://play.golang.org/p/Pt6BN2Mj-WL