Python Shallow Copy
In Python, we create a copy of the already existing objects by using “=” operator with different variable name. By this we have an object with its copy with two different names. If any change is made to one of the object or copy, same change appears in other one too. Sometimes, we need to make original one safe and apply required changes to the copy of original object.
We can create a copy of the object by using copy module. One way of copying objects is shallow copy.
Shallow copy is a collection object which is constructed by populating with the references to the child objects of the original. The copying process of shallow copy is one level deep which means it is not a recurring process. It cannot create copies of the child objects by themselves.
A copy of the object is created by using assignment operator ‘ = ’
Python Code
#creating a list
list1= ["a","b","c","d"]
#creating other list and copying list1
list2=list1
#printing copy list
print(list2)
Output
[‘a’, ‘b’, ‘c’, ‘d’]
Let’s create a copy object by using shallow copy
Python Code
import copy
list1= ["a","b","c","d"]
#creating a copy of list1 using shallow copy
list2=copy.copy(list1)
#printing copy list
print(list2)
#making changes to list2
list2.append("e")
print("after making changes, list2 is:",list2)
print("after making changes, list1 is:",list1)
Output
[‘a’, ‘b’, ‘c’, ‘d’]
after making changes, list2 is: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
after making changes, list1 is: [‘a’, ‘b’, ‘c’, ‘d’]