How does late binding in Python?

Hi all.
Recently stumbled on here is such an example.
def multipliers():
 return [lambda x : i * x for i in range(4)]

print [m(2) for m in multipliers()] # [6,6,6,6]

I received quite an unexpected answer(at least for me).
I would like to understand in this case is called late-binding?
July 8th 19 at 16:19
2 answers
July 8th 19 at 16:21
A typical situation for the combination of a foreach loop + circuit
The fact that the variable i is captured by reference, and a foreach loop on each iteration overwrites its value. Thus it happened that in every lambda i = 3.
July 8th 19 at 16:23
To avoid this you can do this:

def multipliers():
 return [lambda x, i=i: i * x for i in range(4)]

print([m(2) for m in multipliers()]) # [0, 2, 4, 6]

or so

def multipliers():
 return (lambda x: i * x for i in range(4))

print([m(2) for m in multipliers()]) # [0, 2, 4, 6]

The second option in this case I like more.
But first - a universal solution for all such problems with the lambda.

Find more questions by tags Python