Python: difference between shallow copy and deep copy
In this tutorial, we will learn about the Python shallow copy and deep copy method with the help of examples.
Assignment Statement (=)
When we use = operator in Python, we think that this creates a new object; it doesn’t. It only creates a new variable that shares the reference of the original object.
As you can see in this example, both list1 and list1_copy shares the same id. Thus, if you try to modify any values in list1 or list1_copy, the change reflects the other object.
Using = operator will not satisfy the requirement if you want to have toe original values unchanged and only modify the new values or vice versa. In this case, there are two ways to create copies in Python:
- Deep Copy
- Shallow Copy
In order to use those two methods, we should first import copy module.
# Official DocumentA shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A shallow copy creates a new object and stores the reference of the original element. list2 and list2_copy are differenct objects, although they have the same values.
It seems like, if you make changes to the copy list, it will not affect the original list.
However, if you make a shallow copy for a nested object, the elements in the new object are referenced to the original objects. In this case, the changed on the original object will be reflected on the copy object, vice versa.
In the above program, we made changes to list2_copy i.e list2_copy = 8. Both list2 and list2_copy at index  were modified. This is because, both lists share the reference of same nested objects.
# Official Document
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Let repeat the previous list-copying example, but using
deepcopy() function present in
copy module. The deep copy creates independent copy of the original object and all its nested objects.
In the above program, when we assign a new value to
list5 , we can see only
list5 is modified; when we assign a new value to
list5_copy , only
list5_copy is modified. This means, there are independent. You can make any changes on the deep copy object, and it will not modifiy the original object.
Making a deep copy is slower
In the above program, we create 100,000 times shallow copy and 100,000 times deep copy. It takes only 70.9 ms to finish creating shallow copy, however, it takes 1.58s to create deep copy. Because in the deep copy, you are making new copies for every object.
- A deep copy will create a fully independent object from the original, but it is slower
- A shallow copy will not clone a child object, thus, it is not fully independent.