Shallow Copy
Shallow copy creates a new object that references the same underlying data as the original object. It only copies the reference to the object, not the object itself. If the elements in the original object are immutable (e.g., numbers, strings), this distinction is typically not noticeable. However, if the elements are mutable (e.g., lists, dictionaries), modifying mutable elements in the new object affects the original.
Example:
pythonimport copy original_list = [1, 2, [3, 4]] shallow_copied_list = copy.copy(original_list) shallow_copied_list[2][0] = 300 # Output: original_list = [1, 2, [300, 4]] # shallow_copied_list = [1, 2, [300, 4]]
In this example, modifying the nested list in shallow_copied_list affects original_list.
Deep Copy
Deep copy recursively copies the entire object and all its nested objects. This means the original object and the new object are completely independent; modifying one does not affect the other.
Example:
pythonimport copy original_list = [1, 2, [3, 4]] deep_copied_list = copy.deepcopy(original_list) deep_copied_list[2][0] = 300 # Output: original_list = [1, 2, [3, 4]] # deep_copied_list = [1, 2, [300, 4]]
In this example, changes to deep_copied_list do not affect original_list.
Summary
The choice between shallow copy and deep copy typically depends on specific requirements. If you only need to copy the top-level structure and are okay with sharing underlying data, shallow copy may be faster and use less memory. However, if you need a completely independent copy, deep copy is necessary. Using Python's copy module makes it easy to implement both copy methods.