+ 1

How do I copy a list as described under?

I am writing a code in python. This code requires copying a nested list A in B. But when I make changes to the list members of B, these are made to A as well. This problem arises due to the alias effect.

25th Jun 2019, 2:36 AM
Jitender K Yadav
Jitender K Yadav - avatar
3 Respostas
+ 2
Make a shallow copy of the list. If that doesn't work make a deep copy. lst = [[1, 2], [3, 4]] new_list = lst[0] shallow_copy = lst[0][:] lst[0][0] = 42 print(new_list) # [42, 2] print(shallow_copy) # [1, 2]
25th Jun 2019, 3:52 AM
Diego
Diego - avatar
+ 2
Sorry but shallow copy did not work. But I was able to complete the code by using deepcopy function from copy module.
25th Jun 2019, 4:20 AM
Jitender K Yadav
Jitender K Yadav - avatar
+ 1
Sorry but shallow copy did not work. But I was able to complete the code by using deepcopy function from copy module.
25th Jun 2019, 4:20 AM
Jitender K Yadav
Jitender K Yadav - avatar