DEV Community

Aniketh Deshpande
Aniketh Deshpande

Posted on

Shallow Copy Vs Deep Copy

In our day to day development tasks, we come across the need to copy objects and perform various operations.

Python provides two important functions in the copy library - copy and deepcopy.

Let us understand the difference between the two and their respective use cases.

Shallow Copy - copy.copy(obj)

  • It makes a copy of the obj at the surface level.
  • It copies all the contents of the obj.

copy.copy()

  • However, the point to be noted here is that, in case the contents of x are mutable, then, y has reference to the contents of x. Any modification to the contents of x would be reflected in y as well.

shallow copy

In this example we see that modifying the contents of x[1], also modified the contents of y[1].

shallow copy

Similarly, we see that modifying the contents of y, also modified the contents of x.

Deep Copy - copy.deepcopy(obj)

  • Deepcopy copies the object recursively. Recursively means, it copies the contents of the object and not merely its reference.

  • So we should use deep copy in case we need an independent copy of the contents of the obj.

Deepcopy

  • In deepcopy, any changes to the contents of x do not effect y, unlike shallow copy.

Deepcopy


Copying objects properly is a very important basic python concepts. This knowledge helps in building error free code wrt copying objects.

Thank you
Aniketh Deshpande

Top comments (0)