How to deep copy a list in Python?
Table of Contents
- Introduction
- Shallow Copy vs Deep Copy
- How to Perform a Deep Copy in Python
- Practical Examples
- Conclusion
Introduction
In Python, copying lists can be tricky, especially when dealing with nested lists or mutable objects. A deep copy creates an entirely independent copy of the original list, including any nested objects, ensuring that changes to the copy do not affect the original. The most common method for deep copying is using the copy.deepcopy()
function from the copy
module.
Shallow Copy vs Deep Copy
Shallow Copy
A shallow copy creates a new list but only copies references to the objects within the original list. This means that if the list contains mutable objects (like other lists), changes to those objects will be reflected in both the original and the copied list.
Example of Shallow Copy:
In this example, modifying shallow_copy
also alters the original
list due to shared references.
Deep Copy
A deep copy, on the other hand, duplicates everything within the list, including any nested objects, meaning that changes to the copy won’t affect the original list.
How to Perform a Deep Copy in Python
1. Using copy.deepcopy()
The copy.deepcopy()
method from the copy
module is used to create a deep copy of a list. This method recursively copies all objects within the list, making a completely independent copy.
Example of Deep Copy:
Here, changing deep_copy_list
does not affect original
, as they are completely independent.
Practical Examples
Example : Deep Copying a List of Lists
Example : Deep Copy with Mutable Objects
Conclusion
In Python, when working with nested lists or mutable objects, it is important to understand the difference between shallow and deep copies. While a shallow copy only duplicates references to objects, a deep copy creates completely independent duplicates of all objects within the list. The copy.deepcopy()
method is the go-to solution for deep copying lists, ensuring that modifications to the copied list do not affect the original.