A deep copy refers to cloning an object. When we use the
= operator, we are not cloning the object; instead, we reference our variable to the same object (a.k.a. shallow copy).
This means that changing one variable’s value affects the other variable’s value because they are referring (or pointing) to the same object. This difference between a shallow and a deep copy is only applicable to objects that contain other objects, like lists and instances of a class.
To make a deep copy (or clone) of an object, we import the built-in
copy module in Python. This module has the
deepcopy() method which simplifies our task.
This function takes the object we want to clone as its only argument and returns the clone.
import copy # Using '=' operator x = [1, 2, 3] y = x x = 5 # value of 'y' also changes as it is the SAME object x = 15 print "Shallow copy: ", y # Using copy.deepcopy() a = [10, 20, 30] b = copy.deepcopy(a) a = 70 # value of 'b' does NOT change because it is ANOTHER object print "Deep copy: ", b
View all Courses