In the previous article we were talking about shallow copies of lists. We know that only the reference to a sublist is copied if there are nested lists. If we need a full copy, we need a deep copy. Deep copies are the subject of this article.
Here’s the video version of the article:
So, if we want a full copy of a list, along with all the sublists, we need a deep copy. There is a deepcopy method in the module copy, which we have to import:
>>> from copy import deepcopy
>>> sports = ["soccer", "tennis", ["hammer throw", "javelin throw"]]
Now we’ll make a deep copy using the imported method:
>>> sports_copy = deepcopy(sports)
The deepcopy method seems to have worked:
>>> sports
['soccer', 'tennis', ['hammer throw', 'javelin throw']]
>>> sports_copy
['soccer', 'tennis', ['hammer throw', 'javelin throw']]
But let’s check it out. First, let’s change a simple element in the copy. The change should be visible only in the copy:
>>> sports_copy[0] = "football"
>>> sports
['soccer', 'tennis', ['hammer throw', 'javelin throw']]
>>> sports_copy
['football', 'tennis', ['hammer throw', 'javelin throw']]
Works! Now let’s see if the sublist was copied correctly. Let’s change an element in the sublist in the copy:
>>> sports_copy[2][1] = "discus throw"
Now the sublist in the original should remain untouched whereas in the copy we should see the change in the sublist:
>>> sports
['soccer', 'tennis', ['hammer throw', 'javelin throw']]
>>> sports_copy
['football', 'tennis', ['hammer throw', 'discus throw']]
Works! So, a deep copy is the solution to choose if you need a full copy, along with all the nested lists.