In Python, if you want to copy an object, the assignment operator will not serve the purpose. It creates a binding between the target and the object, i.e. it never creates a new object. It just creates a new variable that shares the original object reference. To solve this problem, the replication module is provided. This module has common shallow copy and deep copy operations.
Shallow copy constructs a new composite object and then inserts the reference into the original object. It copies objects using the following method −
copy.copy(x) Return a shallow copy of x.
Deep copy constructs a new composite object and then recursively inserts copies of the objects in the original object into it. It copies objects using the following methods −
copy.deepcopy(x[, memo]) Return a deep copy of x. Here, memo is a dictionary of objects already copied during the current copying pass;
The following problems may occur when using deep copy operations -
Recursion may lead to recursive loops.
Because deep copy copies everything, it is possible to copy too much, such as data that you want to share between replicas.
However, the deepcopy() method avoids these problems. Let’s see how −
Keep the memo dictionary of objects copied during the current copy process
Allow user-defined classes to override the copy operation or set of copied components.
To install the copy module, use pip −
pip install copy
Use the copy module after installation −
import copy
We will use shallow copy to copy the object. It creates a new object to store a reference to the original element. Let’s see an example −
import copy # Create a List myList = [[5, 10], [15, 20]] # Display the list print("List = ", myList) # Shallow Copy myList2 = copy.copy(myList) # Display the copy of the List print("New copy of the list =", myList2)
List = [[5, 10], [15, 20]] New copy of the list = [[5, 10], [15, 20]]
In the above example, we shallowly copied the list using the copy() method.
We will use the deepcopy() method to deep copy the object. A deep copy also creates a new object. Let’s see an example −
import copy # Create a List myList = [[5, 10], [15, 20]] # Display the list print("List = ", myList) # Deep Copy myList2 = copy.deepcopy(myList) # Display the copy of the List print("New copy of the list =", myList2)
List = [[5, 10], [15, 20]] New copy of the list = [[5, 10], [15, 20]]
The above is the detailed content of How to copy objects in Python?. For more information, please follow other related articles on the PHP Chinese website!