TUTORIAL

Shallow/Deep Copy of Data

This section introduces the similarities and differences between deep and shallow copy in Python

On this page

There are two kinds of data copying: shallow copy and deep copy. As can be seen from the names, a shallow copy only copies the pointer to the object, whereas a deep copy copies the entire object into another block of memory.

Shallow Copy

For example, suppose we have a list [1, [1,2,3]]. With a shallow copy, if the second element of the list — the list [1,2,3] — changes, it will make the same change in both the original list and the shallow-copied list, because they point to the same memory address.

A = [1, [1, 2, 3]]
B = A.copy()
A[1].append(4)
print(B)
# Out: [1, [1,2,3,4]]
print(A)
# Out: [1, [1,2,3,4]]
A[1] is B[1]
# Out: True

There are two ways to implement a shallow copy: one is to use the copy() method, and the other is to use the copy function in the copy module.
The list type has another shallow copy method as well: a new list generated through slicing is also the result of a shallow copy.

A = [1, [1, 2, 3]]
B = A[:]
B[1] is A[1]
# Out: True

Deep Copy

A deep copy completely copies the data of the object being copied into new memory. The addresses of the old and new data objects are completely different; they are 100% independent data.

import copy

A = [1, [1, 2, 3]]
B = copy.deepcopy(A)
A is B
# Out: False
A[1].append(4)
print(A, B)
# Out: [1, [1, 2, 3, 4]] [1, [1, 2, 3]]
A[1] is B[1]