Can you explain the difference between shallow copy and deep copy in Python? Provide an example to demonstrate their usage.
Certainly. Shallow copy creates a new object but doesn't recursively copy nested objects, meaning that changes to nested objects in the copied structure will be reflected in the original. Deep copy, however, creates a new object and recursively copies all nested objects, ensuring that changes in the copied structure do not affect the original.
import copy original_list = [[1, 2, 3], [4, 5, 6]] # Shallow copy shallow_copied_list = copy.copy(original_list) # Deep copy deep_copied_list = copy.deepcopy(original_list) original_list[0][0] = 100 print(original_list) # Output: [[100, 2, 3], [4, 5, 6]] print(shallow_copied_list) # Output: [[100, 2, 3], [4, 5, 6]] print(deep_copied_list) # Output: [[1, 2, 3], [4, 5, 6]]
In this example, changes to the nested list are reflected in the shallow copied list but not in the deep copied list.