What is a closure in Python, and why does a closure created inside a loop often capture the wrong value?
Answer
A closure is an inner function that remembers and can access variables from its enclosing function's scope even after the outer function has finished executing, because Python keeps those variables alive in a shared "cell" that the inner function references. Inside a loop, if a lambda or nested function refers to the loop variable directly, every closure created in that loop shares the same cell, so by the time any of the closures are actually called, they all see the loop variable's final value, not the value it had when each closure was created.
Strong answer includes
- inner function retains access to enclosing scope via a shared cell
- loop closures share one cell for the loop variable
- all closures see the loop variable's final value unless bound explicitly
Practical example
Run the code to see the result.
The bad lambdas share one closure cell for i and read its final value later. Binding i as a default argument stores the current value when each lambda is created.
Expected result: [2, 2, 2] followed by [0, 1, 2].