Python performs late binding for variables used in a closure. This means the value of variables are looked up when the closure is called.
Example
For example, when we write
def create_multipliers(): return [lambda x : i * x for i in range(5)] for multiplier in create_multipliers(): print(multiplier(2), end=' ')
We will print 5
8
s rather than0 2 4 6 8
.In this case, even though 5 closures are created, they all look up
i
after thefor i in range(5)
is finished, and the value ofi
in that time is4
.