Welcome to another tutorial. In this tutorial, you will learn the concept of a shallow and deep copy.
To copy the value of one variable to another variable in Python, we can use the operator =, this is the same as in other languages. This operator (i.e. = ) is used to assign some value to a variable currently referenced by some other variable. But, no new copy of the data gets created, instead, the same copy of data is then referenced by two different variables/objects.
old_str = "Hello World!"
new_str = old_str
print("Id of old string:" + old_str +" is: ", id(old_str))
print("Id of new string:" + new_str +" is: ", id(new_str))
Output:
Id of old string:Hello World! is: 139681093231344
Id of new string:Hello World! is: 139681093231344
From the above example, we can see that the same string is getting referenced by both variables. This scenario is not for only strings, it applies to objects, though everything in python is an object.
There is a copy module in python to allows a user to copy an object from one variable to another. We know that if we assign one variable to another, the two variables then refer to a single object. Thus, the copy module in python can be used to manage the copying process of an object.
The copy.deepcopy(x) function is typically employed in performing deep copy in python. It is used to create a deep copy of any object x. An extra individual object is created by taking the data from the main object and replicating it in the new object in a deep copy. Thus, if there is any change in the copied reference, then the main object will remain as it was.
import copy
l1=[1,3,[9,4],6,8]
l2=copy.deepcopy(l1) #Making a deep copy
print('List 1 = ', l1)
print('List 2 = ', l2)
print('Performing change in list 2')
l2[2][0] = 5
print('List 1 = ',l1)
print('List 2 = ',l2)
Output:
List 1 = [1, 3, [9, 4], 6, 8]
List 2 = [1, 3, [9, 4], 6, 8]
Performing change in list 2
List 1 = [1, 3, [9, 4], 6, 8]
List 2 = [1, 3, [5, 4], 6, 8]
From the above, example, the first list ( 11) is a deep copy of 12, the second list. as such, if we update some data item in 12, it will not reflect in 11.
In Python, the copy.copy(x) function is used for performing the shallow copy. It is used to create a shallow copy of any object x. Thus, for shallow copy, a reference of an object is copied to another object. As such if there is any change on the copied reference, it will change the content of the main object as well. It is the same as when you just copy work in Python. Check the example below.
import copy
l1 = [1,3,[9,4],6,8]
l2 = copy.copy(l1) #Making a shallow copy
print('List 1 = ', l1)
print('List 2 = ', l2)
print('Performing change in list 2')
l2[2][0] = 5
print('List 1 = ',l1)
print('List 2 = ',l2)
Output:
List 1 = [1, 3, [9, 4], 6, 8]
List 2 = [1, 3, [9, 4], 6, 8]
Performing change in list 2
List 1 = [1, 3, [5, 4], 6, 8]
List 2 = [1, 3, [5, 4], 6, 8]