Make a Deep Copy of a List in Python
To create a deep copy of a list in Python, use the copy.deepcopy()
method from the copy
module. A deep copy ensures that nested lists (or other mutable objects inside the list) are copied independently, meaning changes in the copied list will not affect the original list.
Examples
1. Creating a Deep Copy Using copy.deepcopy()
The copy.deepcopy()
method recursively copies all nested objects, ensuring that modifying the copied list does not affect the original.
import copy
# Creating a nested list
original_list = [[1, 2, 3], [4, 5, 6]]
# Creating a deep copy using copy.deepcopy()
copied_list = copy.deepcopy(original_list)
# Modifying the copied list
copied_list[0][0] = 99
# Printing both lists
print("Original List:", original_list)
print("Copied List:", copied_list)
In this example:
- We import the
copy
module to use thedeepcopy()
function. original_list
is a nested list containing two inner lists.- We use
copy.deepcopy(original_list)
to createcopied_list
, which is a completely independent copy. - We modify
copied_list[0][0]
(changing1
to99
), butoriginal_list
remains unchanged.
Output:
Original List: [[1, 2, 3], [4, 5, 6]]
Copied List: [[99, 2, 3], [4, 5, 6]]
2. Difference Between Shallow Copy and Deep Copy
A shallow copy (using copy.copy()
or list()
) only copies the outer list, meaning changes in the copied list affect the original if there are nested elements.
import copy
# Creating a nested list
original_list = [[1, 2, 3], [4, 5, 6]]
# Creating a shallow copy
shallow_copy = copy.copy(original_list)
# Modifying the shallow copy
shallow_copy[0][0] = 99
# Printing both lists
print("Original List:", original_list)
print("Shallow Copy:", shallow_copy)
copy.copy(original_list)
creates a new outer list but does not copy inner lists independently.- When we change
shallow_copy[0][0]
, the modification also appears inoriginal_list
, because both lists share the same nested elements.
Output:
Original List: [[99, 2, 3], [4, 5, 6]]
Shallow Copy: [[99, 2, 3], [4, 5, 6]]
Since a shallow copy shares inner lists with the original, changes in one list reflect in the other. To avoid this, use deepcopy()
.
Conclusion
To copy a list in Python:
- Use
copy.deepcopy()
for a deep copy (ensuring a completely independent duplicate). - Use
copy.copy()
orlist()
for a shallow copy (which shares nested elements with the original).
Deep copies are essential when working with nested lists or objects to prevent unintentional modifications to the original data.