Search
  • Antoreep Jana

Understanding Shallow vs Deep Copy




Shallow Copy Duplicate as little as possible


whereas


Deep Copy duplicates everything.



Which means,


By using a shallow copy, two collections now share the individual elements. Whereas by using a deep copy, two individual collections are created with similar individual elements but not shared.



Using Shallow Copy



import copy
data2 = data1.copy()



Using Deep Copy



import copy
data2 = data1.deepcopy()



Difference from Assignment


Assigning variables to objects is just adding another reference to the data object. It doesn't make any copy like shallow or deep.


Practical Usage or Applications


For immutable objects, there is no need for copying because the data will never change, so Python uses the same data; ids are always the same. For mutable objects, since they can potentially change, [shallow] copy creates a new object.


Deep copy is related to nested structures. If you have list of lists, then deepcopy copies the nested lists also, so it is a recursive copy. With just copy, you have a new outer list, but inner lists are references.

22 views0 comments

Recent Posts

See All