3
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,256
  • 1
  • 12
  • 32

2 Answers2

7

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
  • 8,342
  • 4
  • 24
  • 45
-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
  • 433
  • 3
  • 16