What is the late-binding closure trap?hard

Type
conceptual
Topic
closures
Frequency
common
Tags
closures, scope, lambda
Answer

Closures capture the variable, not its value — so all closures created in a loop see the variable's final value, not the value at the time each closure was made.

Explanation

[lambda: i for i in range(3)] creates three lambdas that all reference the same i. When called after the loop, i == 2, so all three return 2. Fix: use a default argument — lambda i=i: i — because default arguments are evaluated at function creation time, capturing the current value immediately.

Follow-upWhy does the default-argument fix work when the closure itself doesn't?