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…

--

--