+ 1
Deep copy in nested lists
Does this way of deep copy b = a[:] works when we have a nested list? because when I try to change one of the item in the nested list after deep copying , it says that two lists are equal. Why is that? a = [1,2,[3,2,5],8] b = a[:] b[2][0] = 9 if a == b: Print (“equal”) else: print (a) print (b)
3 Réponses
+ 1
Because you are not doing a deep copy but a shallow one.
b = a[:] is equivalent to b = [i for i in a]
Deep copy is done by using the deepcopy function in copy module
+ 1
In shallow copy, changes made in one list is reflected in other list.
In deep copy,changes made in one list is not reflected in other list. In the above code, you are shallow copying. So when you do
b[2][0]=9,a[2][0] becomes 9. So the output is equal
import copy
a=[1,2,3,4,5]
b=copy.deepcopy(a)
b[1]=1
if(a==b):
print("equal")
else:
print ("notequal")
Now notequal is printed
0
thank you