4
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?

Alexey
  • 1,366
  • 1
  • 13
  • 33

2 Answers2

12

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)]
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
-1

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]
Zak Stucke
  • 432
  • 6
  • 18