def multipliers():
return [lambda x: i * x for i in range(4)]
print([m(1) for m in multipliers()]) # [3, 3, 3, 3]
Why it's not [0, 1, 2, 3]
? Can't understand. So, for some reason we have i = 3
in all lambdas? Why?
This is because of Pythons late binding closures. You can fix the issue by writing:
def multipliers():
return [lambda x, i=i : i * x for i in range(4)]
Is this what you were trying to do?
def multipliers(x):
return [i * x for i in range(4)]
print(multipliers(1))
>> [0, 1, 2, 3]