Skip to content
Home » Copying Lists – Deep Copies in Python

Copying Lists – Deep Copies in Python

Spread the love

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"

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply