I came across this code which is one of Python's gotchas:
def create_multipliers():
return [lambda x : i * x for i in range(5)]
for multiplier in create_multipliers():
print multiplier(2)
I read the solution here but I am confused at some places. I have two questions:
Why is it printing
8,8,8,8,8instead of0,2,4,6,8?They come up with this solution
def create_multipliers(): return [lambda x, i=i : i * x for i in range(5)]What is
i=idoing and why it used?