Shallow and Deep Copy

Xia Song
3 min readJun 21, 2019

--

  1. Example of shallow copy: list copy

colours1 = [‘red’, ‘blue’]
colours2 = colours1

Shallow Copy

Above example is simply assigned colours1 list to colours2. The list of colours2 is a so-called “shallow list”, because it does not have nested structure.

Assign a New List Element

Above codes showed us, after we assigned a new list object to colour2, the values of colour1 is also changed. The reason why colour1 is also changed is that both colour1 and colour2 point to the same object, and we did not assign a new object to colours2. When we changed one element of colours2 or as it is usually called “in place”. Both variables “colours1” and “colours2” still point to the same list object.

2. Example of shallow copy: slice copy

list1 = [‘a’,’b’,’c’,’d’]
list2 = list1[:]

Assign a New List Element

The slice operator can completely copy shallow list structures without any of the side effects, like the example above. But there will arise issues if a list contains sublists: the sublists can not be copied but only references to the sublist.

list1 = [‘a’,’b’,[‘ab’,’ba’]]
list2 = list1[:]

Slice Copy a Nested List
Assign New List Element

When you changed the element of list rather than the sublist, nothing wrong happend, however, if you change one of the element of sublist, problems arise, and both lst1 and lst2 are affected by the assignment lst2[2][1] = ‘d’.

3. Deepcopy can help to avoid above issues.

Deep Copy

From copy module import deepcopy method. When we use deepcopy to copy nested list structure, we can see by using the id function that the sublist has been copied, becuase id(lst2[2]) is different from id(lst1[2]).

Assign New List Element

After useing deep copy, when you changed the element of sublist only lst2 are affected by the assignment lst2[2][1] = ‘d’.

--

--

Xia Song
Xia Song

No responses yet