The Difference between Shallow Copy and Deep Copy in Python

09/15/2021

Contents

In this article, you will learn about the difference between shallow copy and deep copy in Python.

The difference between shallow copy and deep copy

In Python, when we create a copy of an object, we can either create a shallow copy or a deep copy. The difference between the two is how the copy is created and how it behaves with respect to the original object.

A shallow copy creates a new object, but it does not create new copies of the nested objects within the original object. Instead, it creates references to the nested objects, which means that any changes made to the nested objects will be reflected in both the original and copied objects.

In contrast, a deep copy creates a new object and also creates new copies of any nested objects within the original object. This means that changes made to the nested objects in the copied object will not affect the original object.

Here is an example to illustrate the difference between shallow copy and deep copy:

import copy

original_list = [1, 2, [3, 4]]
shallow_copy_list = copy.copy(original_list)
deep_copy_list = copy.deepcopy(original_list)

# Modifying the nested list in the original list
original_list[2][0] = 5

print(original_list)         # Output: [1, 2, [5, 4]]
print(shallow_copy_list)     # Output: [1, 2, [5, 4]]
print(deep_copy_list)        # Output: [1, 2, [3, 4]]

In the above example, we create an original list with nested objects, including another list. We then create a shallow copy and a deep copy of the original list using the copy module. We then modify the nested list in the original list by changing its first element to 5.

When we print out the three lists, we can see that the shallow copy has been affected by the change to the nested list in the original list, whereas the deep copy has not. This is because the shallow copy only creates references to the nested objects, while the deep copy creates new copies of the nested objects.