How do you Copy an Object in Python?
29/06/2024Copying an object in Python can be done in several ways, depending on the depth of the copy required:
-
Shallow Copy:
A shallow copy creates a new object, but inserts references into it to the objects found in the original. Can be done using the copy module’s copy method or by using the slicing syntax for certain objects.
import copy
# Using copy method
original_list = [1, 2, 3]
shallow_copy = copy.copy(original_list)
# Using slicing (for lists)
shallow_copy_slicing = original_list[:]
-
Deep Copy:
A deep copy creates a new object and recursively adds copies of nested objects found in the original. Can be done using the copy module’s deepcopy method.
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
deep_copy = copy.deepcopy(original_list)
Shallow Copy Example
import copy
original_list = [1, 2, 3, 4]
shallow_copy = copy.copy(original_list)
# Modifying the shallow copy
shallow_copy[0] = 10
print(“Original List:”, original_list) # Output: Original List: [1, 2, 3, 4]
print(“Shallow Copy:”, shallow_copy) # Output: Shallow Copy: [10, 2, 3, 4]
Deep Copy Example
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
deep_copy = copy.deepcopy(original_list)
# Modifying the deep copy
deep_copy[0][0] = 10
print(“Original List:”, original_list) # Output: Original List: [[1, 2, 3], [4, 5, 6]]
print(“Deep Copy:”, deep_copy) # Output: Deep Copy: [[10, 2, 3], [4, 5, 6]]
When to Use Shallow vs. Deep Copy
-
Shallow Copy:
Use when you only need a new container object but want to keep references to the objects contained in the original. Suitable for objects containing primitive data types (integers, strings, etc.) or when the contained objects are immutable.
-
Deep Copy:
Use when you need a completely independent copy of the original object and all objects contained within it. Suitable for nested or complex objects where changes to the copied object should not affect the original.