In Python, the assignment operator (=) creates a reference between the target variable and the object, rather than creating a new copy of the object. To create a copy of an object, you can use the copy module.
There are two types of copies that can be created using this module: shallow copy and deep copy. A shallow copy creates a new object with a copy of the values in the original object, but if the original object contains references to other objects, the shallow copy will only copy the references. A deep copy, on the other hand, creates a completely new copy of the original object, including any referenced objects.
Example
Shallow copy
Here is an example of how to use the copy()
function to create a copy of a list object:
Deep copy
You can also use the deepcopy()
function to create a deep copy of an object, which copies not only the object itself, but also any objects it contains (if it is a container object).