- Example of shallow copy: list copy
colours1 = [‘red’, ‘blue’]
colours2 = colours1
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.
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[:]
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[:]
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.
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]).
After useing deep copy, when you changed the element of sublist only lst2 are affected by the assignment lst2[2][1] = ‘d’.