What is the difference between a shallow copy and a deep copy in Python?
What is the difference between a shallow copy and a deep copy in Python?
What is the difference between a shallow copy and a deep copy in Python?
solveurit24@gmail.com Changed status to publish February 13, 2025
- Shallow copy: Creates a new object and inserts references to the original object’s elements.
- Deep copy: Creates a new object and recursively copies all elements to new objects.
Example:
import copy
original = [[1, 2], [3, 4]]
# Shallow copy
shallow = copy.copy(original)
shallow[0][0] = 5
print(original) # Output: [[5, 2], [3, 4]]
# Deep copy
deep = copy.deepcopy(original)
deep[0][0] = 10
print(original) # Output: [[1, 2], [3, 4]]
Explanation:
- Changes to nested lists in a shallow copy affect the original list.
- Changes to nested lists in a deep copy do not affect the original list.
solveurit24@gmail.com Changed status to publish February 13, 2025