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 than 0 2 4 6 8 .

In this case, even though 5 closures are created, they all look up i after the for i in range(5) is finished, and the value of i in that time is 4.

JavaScript var has the similar behavior1, but this is fixed with let and const.

References

Footnotes

  1. javascript - What is the difference between “let” and “var”? - Stack Overflow