Shallow copy

In the following code, B is a shallow copy of A.

A = [[1], [2]]
B = A[:]
A = [[1], [2]]
B = A.copy()

B[0] = 3

print(A)
print(B)
[[1], [2]]
[3, [2]]
A = [[1], [2]]
B = A.copy()

B[0].append(42)

print(A)
print(B)
[[1, 42], [2]]
[[1, 42], [2]]
import copy

A = [[1], [2]]
B = copy.copy(A)

B[0].append(42)

print(A)
print(B)
[[1, 42], [2]]
[[1, 42], [2]]

Deep copy

import copy

A = [[1], [2]]
B = copy.deepcopy(A)

B[0].append(42)

print(A)
print(B)
[[1], [2]]
[[1, 42], [2]]

Special functions

Shallow copy and deep copy can be respectively user-defined by special functions __copy__ and __deepcopy__.