0

Using the for loop index in a lambda:function(index) causes the function to use the value that index reaches to, not the value that it was set to.

Using Python 3.9.6

command_list = []
for i in range(2):
    print(i)
    command_list.append(lambda:print(i))
command_list[0]()
command_list[1]()

Causes the result:

0
1
1
1

But what I needed/expected to get:

0
1
0
1

How can I get the expected result?

0 Answers0