Deep Copy a List in Python

Samyak Jain Oct 02, 2021 Jul 02, 2021 Python Python List
  1. Use the copy.deepcopy() Function to Deep Copy a List in Python
  2. Use List Comprehension to Deep Copy a List in Python
Deep Copy a List in Python

We can create shallow and deep copies in Python. A deep copy of a list is to create a new list and then recursively insert in it the copies of the original list’s elements. It refers to cloning a list, and any changes made in the original list do not affect the cloned list.

Use the copy.deepcopy() Function to Deep Copy a List in Python

The deepcopy() function from the copy module is used to create a deep copy of the list specified. If we alter this copy, then the contents of the original list remain the same and are not changed.

For example,

import copy
A = [[10, 60], [50, 'Hi'], ['Hello', 5, 80]]
B = copy.deepcopy(A)
A[2][0] = 'World'
A[0][1] = 10
print('List A is : % s' % (A))
print('List B is : % s' % (B))

Output:

List A is : [[10, 10], [50, 'Hi'], ['World', 5, 80]]
List B is : [[10, 60], [50, 'Hi'], ['Hello', 5, 80]]

List B doesn’t get modified after a new value is assigned in list A because list B is a deep copy of List A. List A and list B are independent of each other.

Use List Comprehension to Deep Copy a List in Python

List comprehension in Python is used to create new lists from other iterables like lists, tuples, strings, and more. List comprehension makes the code simple and efficient.

We will essentially do what the deepcopy() function does and recursively create a new copy of the given list in this method.

For example,

A = [2, 4, 6, 8 , 10]
B = [i for i in A]
A[0] = 'Hi'
print('List A is : % s' % (A))
print('List B is : % s' % (B))

Output:

List A is : ['Hi', 4, 6, 8, 10]
List B is : [2, 4, 6, 8, 10]

We can also perform this method without list comprehension and use the for loop in a traditional way. However, it takes more lines of code and more time.

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • What Is the Difference Between List Methods Append and Extend
  • Convert a List to String in Python