How to do shallow and deep copy of a Python list?

In this tutorial, you will learn how to make shallow and deep copies of a Python list.

Shallow copy vs Deep copy in Python

1. Shallow Copy in Python

Shallow copy does not copy objects recursively, it just copies the main object. But if the main object contains other objects, it does not copy the other objects, it only adds the references of those objects.

Python List copy() method

The Python List copy method allows you to make a shallow copy of a list.

>>> a = [1, 2, 3]
>>> b = a.copy()
>>> b[0] = 5
>>> print(a, b)
[1, 2, 3] [5, 2, 3]
>>>

In the following code, you can see that a list contains a list containing 1,2,3, which means the main object contains other objects. So it will not copy the inner objects.

>>> a = [[1, 2, 3], 'Python', 'Java']
>>> b = a.copy()
>>> b[0][1] = 6
>>> print(a, b)
[[1, 6, 3], 'Python', 'Java'] [[1, 6, 3], 'Python', 'Java']
>>>
Python Shallow copy
Python Shallow copy

2. Deep Copy in Python

Deep copy copies the complete list including the inner objects.

With the help of the deepcopy() method, you can make a deepcopy of a list. But, you have to import this method from the copy module.

This deepcopy() method returns the deep copy of the given mutable object.

from copy import deepcopy

a = [[1, 2, 3], 'Python', 'Java']

b = deepcopy(a)

b[0][0] = 5

print(a, b)
[[1, 2, 3], 'Python', 'Java'] [[5, 2, 3], 'Python', 'Java']

Leave a Reply

Your email address will not be published. Required fields are marked *