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.
Two types of copies 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, however, creates a completely new copy of the original object, including any referenced objects.
Here are example code snippets of how you can create a shallow and deep copy using the copy
module:
Shallow copy:
You can use the copy()
function to create a shallow copy of an object:
Deep copy:
You can also use the deepcopy()
function to create a deep copy of an object, which copies the object itself and any objects it contains (if it is a container object).