
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Copy Objects in Python
In Python, if you want to copy object, the assignment operator won't fulfil the purpose. It creates bindings between a target and an object i.e., it never creates a new object. It only creates a new variable sharing the reference of the original object. To fix this, the copy module is provided. This module has generic shallow and deep copy operations.
Shallow Copy
A shallow copy constructs a new compound object and then inserts references into it to the objects found in the original. It uses the following method to copy objects ?
copy.copy(x) Return a shallow copy of x.
Deep Copy
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original. It uses the following method to copy objects ?
copy.deepcopy(x[, memo]) Return a deep copy of x. Here, memo is a dictionary of objects already copied during the current copying pass;
With deep copy operations, the following issues may occur ?
Recursive may cause a recursive loop.
Since deep copy copies everything it may copy too much, such as data intended to be shared between copies.
However, the deepcopy() method avoids these problems. Let's see how ?
Keeps a memo dictionary of objects already copied during the current copying pass
Allow user-defined classes override the copying operation or the set of components copied.
Install and Import the copy module
To install the copy module, use the pip ?
pip install copy
To use the copy module after installing ?
import copy
Copy object with Shallow Copy
Example
We will use the shallow copy to copy objects. It creates a new object storing the reference of the original elements. 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)
Output
List = [[5, 10], [15, 20]] New copy of the list = [[5, 10], [15, 20]]
In the above example, we have shallow copied the list using the copy() method.
Copy object with Deep Copy
Example
We will use the deepcopy() method to Deep Copy the object. Deep copy also creates a new object. Let us 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)
Output
List = [[5, 10], [15, 20]] New copy of the list = [[5, 10], [15, 20]]