#5, First Floor, 4th Street , Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

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.

Process

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.

Sapmle Code

#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)

Screenshots