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 '=' operatorx = [1, 2, 3]y = xx[0] = 5 # value of 'y' also changes as it is the SAME objectx[1] = 15print "Shallow copy: ", y# Using copy.deepcopy()a = [10, 20, 30]b = copy.deepcopy(a)a[1] = 70 # value of 'b' does NOT change because it is ANOTHER objectprint "Deep copy: ", b
Free Resources