Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy index integer using lambda

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!

like image 897
staad Avatar asked Mar 04 '26 07:03

staad


1 Answers

Not quite sure what you are trying to achieve but the reason that it is printing all 4s is because Python uses dynamic name resolution of variables, that is the value of value when the functions are executed (not when it is declared) is used.

If you really need a function to print the value then you need to create a closure, which means creating the function inside another function, e.g.:

def make_closure(v):
    return lambda: print_index(v)

func = [] 
for value in range(5):
    func.append(make_closure(value))

Now this outputs:

In []:
for a in func:
    a()

Out[]:
0
1
2
3
4
like image 58
AChampion Avatar answered Mar 07 '26 04:03

AChampion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!