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
8s rather than0 2 4 6 8.In this case, even though 5 closures are created, they all look up
iafter thefor i in range(5)is finished, and the value ofiin that time is4.
JavaScript var has the similar behavior1, but this is fixed with let and const.