Very simple code:
for f in [lambda x: x*i for i in [1, 2, 3]]:
print(f(1))
returns:
3
3
3
But I would expect to get 1, 2, 3.
I think I know the reason why this happens (lazy evaluation, and the value of i is evaluated only at the end, when the for loop has ended and i=3
), but my question is: is there a way to avoid this "misbehavior" while keeping the list-comprehension syntax?
I tried to use copy.deepcopy()
on i
:
for f in [lambda x: x*deepcopy(i) for i in [1, 2, 3]]:
print(f(1))
but the result is the same.