Shallow Copy vs. Deep Copy in Python

From this tutorial, you will be learning about the differences between Shallow Copy and Deep Copy (Shallow Copy vs. Deep Copy) in Python.

Note: The syntax used in the below section is for Python 3. You may change it to use with a different version of Python.

Shallow Copy vs. Deep Copy

Must Read – 9 Ways to Copy a File in Python

The difference between Shallow and Deep copy

A shallow copy is one which makes a new object stores the reference of another object. While, in deep copy, a new object stores the copy of all references of another object making it another list separate from the original one.

Thus, when you make a change to the deep copy of a list, the old list doesn’t get affected and vice-versa. But shallow copying causes changes in both the new as well as in the old list.

This copy method is applicable in compound objects such as a list containing another list.

The diagram shown below represents the difference between the shallow copy vs. deep copy.

Shallow Copy vs. Deep Copy

How to perform a shallow and deep copy?

When creating a shallow copy, use the assignment operator(=) to create them.

With Copy module, you can create a shallow copy using the below syntax:

import copy
copy.copy(object_name)

For a deep copy, the following code can get used:

import copy
copy.deepcopy(object_name)

In the next section, a few programs are implemented to demonstrate the Copy Module in Python 3.

Program Example

Here is a simple program to demonstrate the difference between Shallow vs. Deep copy.

import copy

a = [ [1, 2, 3], [4, 5, 6] ]
b = copy.copy(a)

c = [ [7, 8, 9], [10, 11, 12] ]
d = copy.deepcopy(c)

print(a)
print(b)

a[1][2] = 23
b[0][0] = 98

print(a)
print(b)

print("\n")

print(c)
print(d)

a[1][2] = 23
b[0][0] = 98

print(c)
print(d)

The output will come as:

Example output

Best,

TechBeamers