In Python, a shallow copy creates a new object that references the original object’s elements. If the elements are mutable objects, changes made to them will be reflected in both the original and copied objects. On the other hand, a deep copy creates a new object with completely independent copies of the original object’s elements. Changes made to the elements of the deep copy will not affect the original object. The
copy module provides functions like
deepcopy() to create shallow and deep copies, respectively.
import copy # Creating a nested list original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Shallow copy shallow_copy = original_list.copy() # Deep copy deep_copy = copy.deepcopy(original_list) # Modifying the original list original_list = 10 # Printing the copies print("Original List:", original_list) print("Shallow Copy:", shallow_copy) print("Deep Copy:", deep_copy)
In this example, we start by creating a nested list called
original_list. It consists of three inner lists.
Next, we make a shallow copy of
original_list using the
copy() method, and a deep copy using the
deepcopy() function from the
After creating the copies, we modify the first element of the first inner list in the
original_list by assigning it a new value of
Finally, we print the original list, the shallow copy, and the deep copy to observe the differences.
Original List: [[10, 2, 3], [4, 5, 6], [7, 8, 9]] Shallow Copy: [[10, 2, 3], [4, 5, 6], [7, 8, 9]] Deep Copy: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Here’s the explanation of the results:
original_listhas been modified, and the first element of the first inner list is now
shallow_copy, also reflects the change because it creates a new list, but the elements are still references to the original objects. Thus, modifying the nested object in the
original_listaffects the shallow copy as well.
deep_copy, creates a completely independent copy of the original list, including all the nested objects. As a result, the modification in the
original_listdoes not impact the deep copy.
In summary, a shallow copy creates a new object but retains references to the original nested objects, whereas a deep copy creates a completely independent copy, including all nested objects.