-1

I am working on a project where I need to generate a list of different functions into a for loop. Trying to do it, I came with a very weird problem, the function is only registred via the indice used in the loop. If I don't use this indice, I don't acceed the good function. I would like to know what happen and if anyone knows how to have a list of function where the functions into the list dosen't depends on the name of the indice used to defined it. Here is my code and my results :

funcs_list = []
for i in range(2):
    func = lambda:i
    funcs_list.append(func)

#Printing the result into a for loop:
print("Printing the result into a for loop:")
for i in range(2):
    print(funcs_list[i]())

#Printing the result without for loop and indices:
print("Printing the result without for loop and indices:")
print(funcs_list[0]())
print(funcs_list[1]())

#Printing the result without for loop with i indices:
print("Printing the result without for loop with i indices:")
i = 0 
print(funcs_list[i]())
i = 1 
print(funcs_list[i]())

#Printing the result without for loop with j indices:
print("Printing the result without for loop with j indices:")
j = 0 
print(funcs_list[j]())
j = 1 
print(funcs_list[j]())

The results :

Printing the result into a for loop:
0
1
Printing the result without for loop and indices:
1
1
Printing the result without for loop with i indices:
0
1
Printing the result without for loop with j indices:
1
1

0 Answers0