Deep copy index integer using lambda

Viewed 435
func = []

for value in range(5):
    func.append(lambda: print_index(value))


def print_index(index_to_print):
    print(index_to_print)


for a in func:
    a()

When I run the code above, the output is

4
4
4
4
4

Why is it not ?

0
1
2
3
4

What can I do to make it like the above.

I have tried importing copy and using copy.deepcopy(index). I didn't work probably since index is an integer.

Is lambda part of the reason it is not working.

Thank you for your help!

2 Answers
Related