What is the difference between a shallow copy and a deep copy in Python?

In Python, a shallow copy creates a new object that references the original object’s elements. If the elements are mutable objects, changes made to them will be reflected in both the original and copied objects. On the other hand, a deep copy creates a new object with completely independent copies of the original object’s elements. Changes made to the elements of the deep copy will not affect the original object. The copy module provides functions like copy() and deepcopy() to create shallow and deep copies, respectively.

Code Example

import copy

# Creating a nested list
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Shallow copy
shallow_copy = original_list.copy()

# Deep copy
deep_copy = copy.deepcopy(original_list)

# Modifying the original list
original_list[0][0] = 10

# Printing the copies
print("Original List:", original_list)
print("Shallow Copy:", shallow_copy)
print("Deep Copy:", deep_copy)
Code Explanation

In this example, we start by creating a nested list called original_list. It consists of three inner lists.

Next, we make a shallow copy of original_list using the copy() method, and a deep copy using the deepcopy() function from the copy module.

After creating the copies, we modify the first element of the first inner list in the original_list by assigning it a new value of 10.

Finally, we print the original list, the shallow copy, and the deep copy to observe the differences.

Output
Original List: [[10, 2, 3], [4, 5, 6], [7, 8, 9]]
Shallow Copy: [[10, 2, 3], [4, 5, 6], [7, 8, 9]]
Deep Copy: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Here’s the explanation of the results:

  • The original_list has been modified, and the first element of the first inner list is now 10.
  • The shallow copy, shallow_copy, also reflects the change because it creates a new list, but the elements are still references to the original objects. Thus, modifying the nested object in the original_list affects the shallow copy as well.
  • In contrast, the deep copy, deep_copy, creates a completely independent copy of the original list, including all the nested objects. As a result, the modification in the original_list does not impact the deep copy.

In summary, a shallow copy creates a new object but retains references to the original nested objects, whereas a deep copy creates a completely independent copy, including all nested objects.