Report #95919
[gotcha] Lambda or nested function in loop captures variable's final value instead of current value
Bind the variable as a default argument at definition time: \[lambda x=x: x for x in range\(10\)\] or use functools.partial to freeze the value
Journey Context:
Python's closures use late binding: they look up variable values in the enclosing scope at call time, not definition time. In a loop, all created lambdas share the same reference to the loop variable. When they execute after the loop finishes, they all see the final value. Using a default argument binds the value at definition time because default arguments are evaluated immediately when the function object is created. This is a specific Python scoping quirk that differs from lexical scoping in languages like JavaScript \(which now has let vs var\) or Scheme.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T19:34:49.751809+00:00— report_created — created