SHALLOW COPY VS DEEP COPY IN PYTHON

In this we are going to learn about Shallow copy vs Deep copy in Python.

Deep Copy in Python:

In Python, a deep copy is a way to duplicate an object such that even if the original and the copied objects are modified
independently, changes in one doesn’t effect the other. It creates a completely new copy of the object, including all nested
objects,rather than just copying references to them.
so,changes made to the copied object doesnot effect the original , and viceversa.

Syntax for Deepcopy:
copy.deepcopy(x)
import copy
li1 = [1, 2, [3,5], 4]
li2 = copy.deepcopy(lil)
print ("The original elements before deep copying")
for i in range(0, len(lil)):
    print (lil[i],end=" ")
print("\r")
li2[2][0] = 9
print ("The new list of elements after deep copying ")
for i in range(0,len( lil)):
    print (li2[i],end=" ")
print("\r")
print ("The original elements after deep copying")
for i in range(0,len( li1)):
    print (li1[i],end=" ")
output:
The original elements before deep copying
1 2 [3, 5] 4
The new list of elements after deep copying
1 2 [9, 5] 4
The original elements after deep copying
1 2 [3, 5] 4

Shallow copy in Python:

A shallow copy in python is like making a duplicate of an object,but it’s not as deep as a deep copy. It copies the
object itself and any references it contains ,but it doesn’t make copies of the nested objects. so, if you change
something in the copied object,it might affect the original object, especially if they share nested objects.

Syntax for Shallow Copy:
copy.copy(x)
import copy
li1 = [1, 2, [3, 5], 4]
li2 = copy.copy(li1)
print ("The  original elements before shallow copying")
for i in range(0,len(li1)):
    print (li1[i],end=" ")
print("\r")
li2[2][0] = 9
print ("The original elements after shallow copying")
for i in range(0,len(li1)):
    print (li1[i],end=" ") 
output:
The original elements before shallow copying
1 2 [3, 5] 4
The original elements after shallow copying
1 2 [9, 5] 4
Shallow Copy vs Deep Copy:
  • In shallow copy ,the original object is stored and only the reference address is finally copied.But in the case of
    deep copy ,the original object and the repetitive copies both are stored
  • Deep copy copies all the class members .But in shallow copy , only nested class handles will be copied
  • Shallow copy is faster as compared to Deep copy.
  • Original object and the copied object are not 100% disjoint , but in the case of Deep copy Original object
    and the copied object are 100% disjoint

Leave a Comment

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

Scroll to Top