Shallow vs Deep Copy in Python

#python #datascience

Akash Borgalli Apr 14 2021 · 2 min read
Share this

Shallow Copy:

To implement Shallow copy and Deep copy you need to have data as collections and it should have mutability property.

For Example:- Lists and Dictionaries


We think using  =  operator we are copying items from one variable to another variable or object but we are wrong actually what we are doing is referencing the new variable to the same variable. In short, both variables are sharing the same memory location.

Figure 1

In Figure 1  shown above, we did changes in list 2 at index1 which got reflected in the list1.

Figure 2


To overcome this problem we use the copy function. This function takes one parameter as a list to copy all the items of the list to a new list where we want to store them. Basically, creating a new memory location to store items in a list.

Figure 3

If we observe in Figure 2, we changed the value of list2 which is at index 2 with 456 and this change is reflected only in list 2, not in list 1.

The disadvantage of Shallow copy:

In a scenario, where we have a nested list and if we try to manipulate data inside the nested list the changes are reflected in both the list because as it creates a reference of the object. Here, the copy function fails when manipulating data inside a nested list.

Figure 4

In Figure 3, we did changes in Nlst1 where the changes are reflected in both the list.

The solution to the disadvantage of copy function:

To solve this problem, we have a deep copy function that takes one parameter as a list. This function first creates a new object and then recursively tries to copy items from the original list.

Figure 5

Looking at Figure 4, we have imported the copy module and then use the deep copy function on the object where we want to copy. As you can see we manipulated items of Nlst1 the changes aren't reflected in Nlst2.

Figure 6


Shallow copy works well with a normal(1-D) list whereas if you want to manipulate data inside a nested list use the deep copy function.


Read next