Understanding Shallow Copy and Deep Copy in Python
Mastering Python Object Copying: Learn the Difference Between copy and deepcopy
While coding, a lot of times we encounter situations where weβre supposed to copy objects. For this, we use copy module in Python, which comes as a part of standard Python package. This module provides two methods, copy() and deepcopy(). Both methods help in duplicating the objects, however they significantly differ in how they handle objects nested elements.
βΆοΈ Shallow Copy (copy)
A shallow copy creates a new object but does not create the copies of nested objects within the original object. It actually inserts references to original objects found at the top level.
ππ»ββοΈ How to create a Shallow Copy in Python?
This is done using the copy method from copy module. Hereβs the example on a simple 1D list :
However, if we apply this on a nested list, the nested objects wonβt get copied. Hereβs the example :
The object diagram under the hood looks like below :
βΆοΈ Deep Copy (deepcopy)
A deep copy creates a new object and also recursively create the copies of nested objects within the original object. This is used when you need a completely independent clone of original object.
ππ»ββοΈ How to create a Deep Copy in Python?
This is done using the deepcopy method from copy module. Hereβs the example on a simple 1D list :
Even if we apply this on a nested list, all the nested objects get copied. Hereβs the example :
The object diagram under the hood looks like below :
βΆοΈ Comparison Table
Both copy and deepcopy serve specific purposes in Python. Understanding when and how to use them will help you write cleaner and more efficient code, especially when working with complex data structures.
Remember, if you only need a copy at the top level, go with a shallow copy (copy.copy()); if you need a completely independent clone of all nested objects, go with a deep copy (copy.deepcopy()).
Hope this helps!