What is the difference between shallow and deep copying in Python?

In Python, when you need to create a copy of an object, you can use either shallow copying or deep copying. The main difference between the two lies in how they handle nested objects.

1. Shallow Copying:
- Shallow copying creates a new object but does not create new objects for the elements within the original object. Instead, it just copies the references to those objects.
- Therefore, if you modify a nested object in the copied object, it will reflect those changes in the original object as well.
- In Python, you can create a shallow copy using the `copy()` method or the `copy` module.



import copy

original_list = [1, [2, 3], 4]
shallow_copied_list = copy.copy(original_list)

# Modifying the nested list in the shallow copied list
shallow_copied_list[1][0] = 5

print(original_list) # Output: [1, [5, 3], 4]



2. Deep Copying:
- Deep copying creates a new object and recursively creates new objects for all the elements within the original object, including nested objects. This means that the copied object is fully independent of the original object.
- Any changes made to the nested objects in the copied object will not affect the original object.
- In Python, you can create a deep copy using the `deepcopy()` function from the `copy` module.



import copy

original_list = [1, [2, 3], 4]
deep_copied_list = copy.deepcopy(original_list)

# Modifying the nested list in the deep copied list
deep_copied_list[1][0] = 5

print(original_list) # Output: [1, [2, 3], 4]



In summary, shallow copying creates a new object and references the nested objects, while deep copying creates a new object with copies of all nested objects. The choice between shallow and deep copying depends on whether you want changes in nested objects to reflect in both the original and copied objects or not.
What is the difference between shallow and deep copying in Python?

Related Questions