Trusted answers to developer questions

How to make a deep copy in Python

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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

RELATED TAGS

deep
copy
python
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?