Deep Copy vs Shallow Copy in Python

Posted by Afsal on 10-Jun-2022

Hi Pythonistas!

Today, we will learn the difference between copy and deepcopy functions in Python.

We know that in python assignment doesn't create an object instead create another reference only

Consider the example

a = "test"
b = a
print(id(a))
print(id(b))

output

140095395571184
140095395571184

This means both refer to the exact memory location. To create a new clone of the object we need to use the copy and deepcopy function in the copy module. The difference between copy and deepcopy is that deepcopy recursively creates objects inside the parent object.

Let us consider the example

a = [1, 2, 3, 4, 5]
b = copy.copy(a)
b[0] = 100
print(a)
print(b)

c = [[1, 2, 3], 4, 5, 6]
d = copy.copy(c)
d[0][0] = 100
print(c)
print(d)

Output

[1, 2, 3, 4, 5]
[100, 2, 3, 4, 5]
[[100, 2, 3], 4, 5, 6]
[[100, 2, 3], 4, 5, 6]

If the first case a is a flat list, a copy will create a new list b so changing value in list b does not affect in a. But in the second case, there is another list inside the list c but the copy does not create objects for the child element hence the changing value in d will affect c. In this case, deepcopy is the solution

Consider the example

e = [[1, 2, 3], 4, 5, 6]
f = copy.deepcopy(e)
e[0][0] = 100
print(e)
print(f)

Output

[[1, 2, 3], 4, 5, 6]
[[100, 2, 3], 4, 5, 6]

Here in this example, we used deep copy, deep copy will create objects recursively so change in list e will not affect f.

Use copy for flat object structure and for nested structure use deepcopy. Hope you have learned something from the post. Please share your suggestion with afsal@parseltongue.co.in