I'm trying to add lambdas to a list to be able to be called later. I have an example below but it is not working as expected. Only the last value in the loop is being used for the lambda calls in the list.
Code:
def print_value(x):
print(x)
lambdas = []
for i in range(3):
lambdas.append(lambda : print_value(i))
# Later on try to run the lambdas
for l in lambdas:
l()
Output:
## Expected output
# 0
# 1
# 2
## Actual output
# 2
# 2
# 2
Why is my output not the expected output? I'm setting the value i
in the initial loop and it's only taking the last value.