How to make a deep copy in Python

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.


Method

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.

Syntax

This function takes the object we want to clone as its only argument and returns the clone.

Syntax of copy.deepcopy()
Syntax of copy.deepcopy()
Shallow copy
Shallow copy
Deep copy
Deep copy

Example

import copy
# Using '=' operator
x = [1, 2, 3]
y = x
x[0] = 5 # value of 'y' also changes as it is the SAME object
x[1] = 15
print "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 object
print "Deep copy: ", b

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved