0

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.

mojo1mojo2
  • 1,062
  • 1
  • 18
  • 28
  • 1
    change to `lambdas.append(lambda i=i: print_value(i))` – eyllanesc Jul 23 '19 at 04:26
  • Thank you @eyllanesc that worked! What is happening under the hood? edit: This is duplicated, I'll have a look at the other answers. – mojo1mojo2 Jul 23 '19 at 04:31
  • The idea of marking a duplicate is to save time for everything, you already saved time by finding an answer in a short time, now you save the time to explain to the community by reviewing the answers to the other questions, bye. – eyllanesc Jul 23 '19 at 04:32
  • `i` binds to the global `i`, which at the end of the loop is 2. Need to bind it to local value for each iteration. – mojo1mojo2 Jul 23 '19 at 04:42

0 Answers0