Late-Binding in Closures: A Common Trap
Lambdas defined inside loops often capture the loop variable by reference. We walk through the trace and show a safe pattern to capture the current value.
funcs = [lambda: i for i in range(3)] print([f() for f in funcs]) # prints [2,2,2]
Why it prints [2,2,2]
The lambda captures the name `i`, not its value at definition time. When the lambdas run, `i` has the final loop value (2), so each lambda returns 2.
Fix: capture by default parameter
funcs = [lambda i=i: i for i in range(3)] print([f() for f in funcs]) # prints [0,1,2]
Companion video:
Return to Practice Python Late Binding Explained in 30 Seconds
Short explainer: shows the lambda late-binding trap and a simple fix.