This post will discuss how to get a deep copy of a list in Python.

There are several functions to perform shallow copy operation in Python, as discussed in the previous post. This article explores different ways to perform generic deep copy operations in Python. Before we start, let’s discuss some of the cons of a shallow copy.

A shallow copy only copies the list itself but does not change references to any mutable objects in the list. Consider the following code, where a shallow copy is made from a list of lists using the in-built copy function. Note that when the original list is changed, the change is reflected in both lists.

Download  Run Code

 
Here’s another example where you can see this behavior:

Download  Run Code

 
To avoid this non-deterministic behavior, you need a deep copy of the list. The copy module provides routines for shallow and deep copy operations. A deep copy can be made using copy.deepcopy() function.

Download  Run Code

 
This works by constructing a new object and then recursively inserting copies of the objects found in the original. Note that a deep copy may result in the recursive loop for recursive objects, i.e., compound objects that contain a reference to themselves.

That’s all about getting a deep copy of a list in Python.