Python: Deep and Shallow Copy

Rahul S
2 min readSep 25, 2023

In Python, the = (assignment) operation does not pass by reference. Instead, it binds a new name to the same object.

This behavior is more accurately described as creating a reference to the object. When dealing with mutable objects like lists, modifying the object through any reference will affect all references to that object.

Consider the following example:

A = [1, 2, 3]
B = A # B is now a reference to the same list as A

B.append(4)
print(A)

# Output: [1, 2, 3, 4] - A is also modified

As shown in the example, both A and B refer to the same list, so modifying the list through B also changes A.

Copying Lists in Python:

So, if we want to create a copy of a list without affecting the original list, we can use the copy module in Python.

Shallow Copy

A shallow copy of a list copies the top-level elements but not the nested elements. We can create a shallow copy using list.copy():

A = [1, 2, [3, 4]] #a list
B = A.copy() # Shallow copy of A

B[0] = 100 # Modify B[0]
B[2][0] = 300 # Modify B[2][0]

print(A)
# Output: [1, 2, [300, 4]] - A is partially affected

In a shallow copy, the first-level elements are copied, but any nested objects are still assigned by reference.

Deep Copy

A deep copy of an object copies both the top-level and all nested elements, creating a completely independent copy. You can create a deep copy using copy.deepcopy():

import copy

A = [1, 2, [3, 4]]
B = copy.deepcopy(A) # Deep copy of A
B[0] = 100 # Modify B[0]
B[2][0] = 300 # Modify B[2][0]
print(A) # Output: [1, 2, [3, 4]] - A remains unchanged

With deep copy, changes made to B do not affect A because B is a complete copy of A, including all nested objects.

Conclusion

In Python, the = operator binds names to objects, not values, which means that multiple names can refer to the same object.

To create true copies of objects, we should use the copy.copy() method for shallow copies or copy.deepcopy() for deep copies. Keep in mind that deep copying large objects can be time-consuming, so use it judiciously.

--

--