How to do shallow copy and deep copy in python?

Description

To see how to copy elements from one list to another list using python3.

Shallow copy:

   A shallow copy creates a new object
  which stores the reference of the 
original elements.

    Shallow copy doesn't create a copy of
 nested objects, instead it just copies
 the reference of nested objects.

Deep copy:

     A deep copy creates a new object and
 recursively  adds the copies of nested
 objects present in the  original elements.

#copy a list using = operator
print(“****Copy using assignment operator****”)
list1=[[15,19,20],[25,24,26],[11,10,12]]
#copying the list1 using = operator
newlist=list1
print(“original list is\n”,list1)

list1[1][1]=’s’
print(“new list is\n”,newlist)

#shallow copy
print(“*******Shallow copy*******”)
import copy
list1=[[15,19,20],[25,24,26],[11,10,12]]
#copy the list1 using copy()
newlist=copy.copy(list1)
list1[1][1]=’a’
print(“original list is\n”,list1)
print(“new list is\n”,newlist)

#deep copy
import copy
print(“*******Deep copy*******”)
list1=[[15,19,20],[25,24,26],[11,10,12]]
#copy the list1 using deepcopy()
newlist=copy.deepcopy(list1)
list1[1][1]=’t’
print(“original list is\n”,list1)
print(“new list is\n”,newlist)

Leave Comment

Your email address will not be published. Required fields are marked *

clear formSubmit