Deep vs shallow copy
1 min readAug 6, 2020
There is two types of copying objects in Python: deep and shallow. Here I will show how to perform both of them using built-in module copy.
Import module copy in your code
import copy
Try shallow copy
a = [4]b = copy.copy(a)
>>> b
[4]
>>> id(a)
140122699353672
>>> id(b)
140122699353864
Let’s see how it works on deeply nested lists
>>> a = [[1], [2], [3]]
>>> b = copy.copy(a)
>>> a.append([6])
>>> a
[[1], [2], [3], [6]]
>>> b
[[1], [2], [3]]
>>> a[2][0] = 4
>>> a
[[1], [2], [4], [6]]
>>> b
[[1], [2], [4]]
Change of element a[2][0] leading to change in corresponding element b[2][0] as all nested lists in a are passed as reference on default.
Now let’s try deep copying:
>>> b = copy.deepcopy(a)
>>> a
[[1], [2], [4], [6]]
>>> b
[[1], [2], [4], [6]]
>>> a[2][0] = 8
>>> a
[[1], [2], [8], [6]]
>>> b
[[1], [2], [4], [6]]
>>>
We can see that when changing element with index [2][0] in a corresponding element in b is not changing as all nested lists in a are copied to b (nor passed by reference).