Shallow copying and deep copying are two ways to make copies of objects in Python. Let's look at the differences between them with examples, especially for tuples:
Shallow Copying:
Shallow copying creates a new object but does not create copies of nested objects. Instead, it copies references to the nested objects.
If the original tuple contains mutable objects (like lists), changes made to the nested objects in the copied tuple will affect the original tuple and vice versa.
Shallow copying can be performed using the
copy()
method or thecopy
module'scopy()
function.
import copy
original_tuple = ([1, 2], [3, 4])
shallow_copy_tuple = copy.copy(original_tuple)
# Modifying the nested list in the shallow copy
shallow_copy_tuple[0].append(5)
print("Original Tuple:", original_tuple) # Output: ([1, 2, 5], [3, 4])
print("Shallow Copy Tuple:", shallow_copy_tuple) # Output: ([1, 2, 5], [3, 4])
Deep Copying:
Deep copying creates a completely independent copy of the original object, including all nested objects. Changes made to the nested objects in the copied tuple do not affect the original tuple, and vice versa.
Deep copying can be performed using the
deepcopy()
function from thecopy
module.
import copy
original_tuple = ([1, 2], [3, 4])
deep_copy_tuple = copy.deepcopy(original_tuple)
# Modifying the nested list in the deep copy
deep_copy_tuple[0].append(5)
print("Original Tuple:", original_tuple) # Output: ([1, 2], [3, 4])
print("Deep Copy Tuple:", deep_copy_tuple) # Output: ([1, 2, 5], [3, 4])
In summary:
Shallow copying creates a new object with references to the nested objects, so changes to nested objects in one tuple affect the other.
Deep copying creates an entirely new object with copies of all nested objects, so changes to nested objects in one tuple do not affect the other.