Q8: Explain the difference between shallow copy and deep copy in Python, and provide examples of scenarios where each is appropriate.
A8:
Shallow Copy:
- A shallow copy creates a new object, but does not create new objects for the elements within the original object. Instead, it copies references to the objects contained in the original.
- Changes made to mutable objects within the shallow copy will be reflected in both the original and the shallow copy.
pythonimport copy original_list = [1, [2, 3], 4] shallow_copy = copy.copy(original_list) # Modify a mutable object within the shallow copy shallow_copy[1][0] = 'X' print(original_list) # Output: [1, ['X', 3], 4]Deep Copy:
- A deep copy creates a new object and recursively creates new objects for all the elements within the original object. It ensures that changes made to mutable objects within the deep copy do not affect the original.
pythonimport copy original_list = [1, [2, 3], 4] deep_copy = copy.deepcopy(original_list) # Modify a mutable object within the deep copy deep_copy[1][0] = 'Y' print(original_list) # Output: [1, [2, 3], 4]
Appropriate Scenarios:
- Use a shallow copy when you want a new object with references to the same objects as the original, suitable for scenarios where immutability is guaranteed.
- Use a deep copy when you want a completely independent copy of the original object, suitable for scenarios where you need to modify objects within the copy without affecting the original.