Python: difference between shallow copy and deep copy

Jack Dong
4 min readDec 29, 2021

In this tutorial, we will learn about the Python shallow copy and deep copy method with the help of examples.

Assignment Statement (=)

When we use = operator in Python, we think that this creates a new object; it doesn’t. It only creates a new variable that shares the reference of the original object.

As you can see in this example, both list1 and list1_copy shares the same id. Thus, if you try to modify any values in list1 or list1_copy, the change reflects the other object.

Using = operator will not satisfy the requirement if you want to have toe original values unchanged and only modify the new values or vice versa. In this case, there are two ways to create copies in Python:

  • Deep Copy
  • Shallow Copy

In order to use those two methods, we should first import copy module.

Shallow Copy

# Official DocumentA shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in…

--

--

No responses yet