Deep Copy Vs Shallow copy
Pritam kumar Tripathy
Assistant Manager Maruti Suzuki | Ex Tata Technologies | Data Scientist | Machine Learning | Python| Automotive
A shallow copy in Python creates a new object but it does not create copies of the nested objects within the original objects. instead, it copies the reference to the nested object.
A Deep copy in Python creates a new object & and recursively copies all objects found in the original object and its nested objects, in other words, it creates a completely independent copy of the original object and all objects contained within it.
If you apply a shallow copy to a nested list, the outer list(i.e. list1 and list2) will be different objects, but the inner list still refers to the same memory location. This is because a shallow copy creates a new outer list but copies refer to the same inner object such as other lists rather than creating new copies of the inner objects.
With Deep copy modifying list2 does not affect list1 because completely independent copies of the nested lists are created.
#python #copy #dataanalysis #deepcopy #shallowcopy #programming #linkedin #article #dataanlytics
Shallow copy inside nested
list1=[[10,11,12],[13,14,15]]
list2=list1.copy()
list2[1][0]=8
print(list1,list1)
([[10, 11, 12], [8, 14, 15]], [[10, 11, 12], [8, 14, 15]])
Deep copy inside nested
import copy
list1=[[78,88,98],[55,45,65]]
list2=copy.deepcopy(list1)
list2[1][0]=35
print(list2,list1)
([[78, 88, 98], [35, 45, 65]], [[78, 88, 98], [55, 45, 65]])