Report #43869
[gotcha] Lambda or def in loop captures loop variable by reference, not value
Use default argument to bind at definition time: \`lambda x=i: ...\` or \`functools.partial\(func, i\)\`
Journey Context:
Python looks up variable names at call time, not definition time. In a loop, all closures share the same binding which mutates on each iteration. Default arguments are evaluated once when the function object is created, effectively capturing the current value. This is the only syntactic way to force early binding without a factory function. Alternatives like storing values as attributes or using \`partial\` are more explicit but verbose; list comprehensions that define functions also work because they create a new scope each iteration.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T04:06:20.668191+00:00— report_created — created