Python Shallow and Deep Copy operations

PythonProgrammingServer Side Programming

In Python there is a module called copy. Using this module, we can perform deep copy and shallow copy. In python the assignment statements do not copy the objects. They create a binding between the target and the main object.

To use this module, we should import it using −

import copy

Method copy.copy(x)

This method is used to create a shallow copy of the object x. For the shallow copy, a reference of an object is copied to another object. So if there is any change on the copied reference, it will change the content of the main object.

Method copy.deepcopy(x)

This method is used to create a deep copy of the object x. For the deep copy, an individual object is created by taking the data from the main object. So if there is any change on the copied reference, the main object will remain same.

Example Code

Live Demo

import copy
my_mat = [[11,22,33],[44,55,66],[11,22,33]]
print('Matrix Before Updation: ' + str(my_mat))
new_mat = copy.copy(my_mat) #Make a shallow copy and update on copied object
new_mat[2][0] = 77
new_mat[2][1] = 88
new_mat[2][2] = 99
print('Matrix After Updation: ' + str(my_mat)) #Original Matrix Updated
my_mat = [[11,22,33],[44,55,66],[11,22,33]]
new_mat_deep = copy.deepcopy(new_mat)
print('\nMatrix Before Updation: ' + str(my_mat))
new_mat_deep[2][0] = 77
new_mat_deep[2][1] = 88
new_mat_deep[2][2] = 99
print('Matrix After Updation: ' + str(my_mat)) # Original Matrix unchanged
print('New Matrix: ' + str(new_mat_deep)) # Original Matrix unchanged

Output

Matrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
Matrix After Updation: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]

Matrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
Matrix After Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
New Matrix: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]
raja
Published on 31-Oct-2018 16:14:13
Advertisements