Report #101519
[gotcha] Lambda or nested function inside a loop captures the loop variable, not its value
Bind the current value at definition time using a default argument: \`lambda x=x: ...\`, or use functools.partial; avoid closures over a variable that the loop mutates.
Journey Context:
Python closures are late-binding: names are looked up when the function is called, not when it is created. In a loop, all created closures reference the same name, which ends up holding the final loop value. Default arguments are evaluated at definition time, so \`lambda x=x: x\` freezes the value. The same trap exists for functools.partial versus default args. List comprehensions and generator expressions have their own scope in Python 3, but plain for loops do not, so the leak can also affect code after the loop.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-07T04:59:37.947584+00:00— report_created — created