Late-binding closures inside a loop
Predict what the list comprehension prints when all lambdas are called.
Code Snippet
funcs = [lambda x: x * i for i in range(3)]
print([f(10) for f in funcs])Expected Output & Explanation
[20, 20, 20] Python closures capture the variable binding i, not its value at each iteration. By the time the lambdas run, the loop has finished and i is 2, so every function multiplies by 2. Fix with default arg capture: lambda x, i=i: x * i.
Follow-up Interview Question · Why does lambda x, i=i: x * i bind each iteration’s value?
Module Context & References
Python · Predict the output & bug traps Widely asked Python gotchas: defaults, closures, scoping, copies and async
Personal Notes · Markdown