![]() |
VOOZH | about |
copy module in Python provides essential functions for duplicating objects. It allows developers to create both shallow and deep copies of objects ensuring that modifications to the copy do not inadvertently affect the original object (or vice versa). This functionality is particularly useful when working with complex data structures like lists, dictionaries and custom objects that contain nested or mutable elements.
Table of Content
To use the copy module, you have toi first import it in your Python script by the following command:
import copy
Syntax:
copy.copy(obj)
Syntax:
copy.deepcopy(obj)
A shallow copy creates a new compound object but the elements contained within are references to the same objects found in the original. This means that for nested objects, changes in the copied object may reflect in the original.
Original: [1, 2, ['Changed', 4]] Shallow Copy: [1, 2, ['Changed', 4]]
Explanation: nested list [3, 4] was not duplicated but referenced, so modifying it in the copy also changes it in the original.
A deep copy creates a new object and recursively copies all nested objects found within the original. This results in an entirely independent object with no shared references.
Original: [1, 2, [3, 4]] Deep Copy: [1, 2, ['Changed', 4]]
Explanation: nested list is fully duplicated. Changes made in the deep copy do not affect the original list.
Use a Shallow Copy When:
Use a Deep Copy When: