Get a deep copy of a Python list
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if __name__ == '__main__': x = [[1, 2], [3, 4], [5]] # create a copy of x clone = x.copy() # remove last item from the second list x[1].pop() # cloned list is also changed print(clone) # [[1, 2], [3], [5]] |
Here’s another example where you can see this behavior:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if __name__ == '__main__': x = [1, 2] y = [x, x] # create a copy of list y clone = y.copy() # remove the last item from the original list x.pop() # cloned list is also changed print(clone) # [[1], [1]] |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from copy import deepcopy if __name__ == '__main__': x = [1, 2] y = [x, x] # create a copy of list y clone = deepcopy(y) # remove the last item from the original list x.pop() # cloned list remains unchanged print(clone) # [[1, 2], [1, 2]] |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)