What is the difference between a shallow copy and a deep copy of a nested list with nested mutable elements in Python using the copy module?Richard W
In Python, when dealing with nested lists that contain mutable elements (such as lists or dictionaries), you have the option to create shallow copies or deep copies. The difference between the two lies in how they handle the references to the nested mutable elements. Let's explore the concepts of shallow copy and deep copy using thecopy
module:
Shallow Copy:
- A shallow copy creates a new list object but maintains references to the original nested mutable elements.
- If you modify one of the nested mutable elements in the shallow copy, the change will be reflected in the original list as well.
- Shallow copy can be performed using thecopy()
method from thecopy
module or the list's slice notation.
Here's an example to demonstrate shallow copy using thecopy
module:
1 2 3 4 5 6 7 8 9 10 11 12
import copy original_list = [[1, 2], [3, 4]] shallow_copy = copy.copy(original_list) # Modifying a nested list in the shallow copy shallow_copy[0][0] = 10 print(original_list) # Output: [[10, 2], [3, 4]] print(shallow_copy) # Output: [[10, 2], [3, 4]]
In the example, modifying the value10
in the shallow copy's nested list also affects the original list. This behavior occurs because both the original list and the shallow copy reference the same nested mutable elements.
Deep Copy:
- A deep copy creates a completely independent copy of the original list and its nested mutable elements.
- If you modify a nested mutable element in the deep copy, the original list remains unchanged.
- Deep copy can be performed using thedeepcopy()
method from thecopy
module.
Here's an example to demonstrate deep copy using thecopy
module:
1 2 3 4 5 6 7 8 9 10 11 12
import copy original_list = [[1, 2], [3, 4]] deep_copy = copy.deepcopy(original_list) # Modifying a nested list in the deep copy deep_copy[0][0] = 10 print(original_list) # Output: [[1, 2], [3, 4]] print(deep_copy) # Output: [[10, 2], [3, 4]]
In this example, modifying the value10
in the deep copy's nested list does not affect the original list. The deep copy creates a new list object with its own independent copies of the nested mutable elements.
When you perform a shallow copy, the new list object references the same nested mutable elements as the original list. However, a deep copy creates a new list object and recursively copies all nested mutable elements, creating separate and independent copies.
To summarize, a shallow copy of a nested list maintains references to the original nested mutable elements, while a deep copy creates completely independent copies of both the list and its nested mutable elements. Understanding the distinction between shallow copy and deep copy is crucial when working with nested lists to ensure that modifications do not unintentionally affect the original data.