Copy in Python
Introduction
In Python, the assignment operator does not create a copy of the object to the target, it creates a binding or a link between the target and the object. When we = operator, it creates a reference of the object to the newly created variable. In Python, there is a copy module that we can use to create real copies or clones of these objects.
Syntax
Deep copy
copy.deepcopy(x) |
Shallow copy
copy.copy(x) |
Example
In Python, we use copy module to make a clone or real copy of an object. This module consists of two methods:
copy(): This method returns a shallow copy of the list.
deepcopy(): This method returns a deep copy of the list.
Code
# Importing the module |
Output
l2 ID: 2521878674624 Value: [1, 2, [3, 5], 4] |
As we can see above, the IDs of list 2 and list 3 are different but the list is the same.
Deepcopy
In Python, deep copy before copying the item first creates a compound object and then recursively inserts the copies. In simple words, it means that first, it constructs a new collection object and then it fills that collection with copies of all the items or child objects of that original one into that newly created collection.
In the case of deep copy, first, a copy of the object is created and then that copy is copied into another object. So any changes made to the copy do not reflect in the original.
Code
import copy # Importing the module |
Output
The original elements before deep copying |
Shallow Copy
In Python, shallow copy also creates a compound object but references the objects of the original object into the new object. In simple words, first, it constructs a collection object, and then it stores the reference of each item or element of the original one in the new collection created. This process is not done recursively hence it will not create copies of the child objects.
In the case of the shallow copy, a reference of each element of the original object is stored in the newly created collection object. Hence changes made to the copied collection will reflect in the original object.
Code
# importing the module |
Output
The original elements before shallow copying |