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.
copy.deepcopy() Function to Deep Copy a List in Python
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.
import copy A = [[10, 60], [50, 'Hi'], ['Hello', 5, 80]] B = copy.deepcopy(A) A = 'World' A = 10 print('List A is : % s' % (A)) print('List B is : % s' % (B))
List A is : [[10, 10], [50, 'Hi'], ['World', 5, 80]] List B is : [[10, 60], [50, 'Hi'], ['Hello', 5, 80]]
B doesn’t get modified after a new value is assigned in list
A because list
B is a deep copy of 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.
A = [2, 4, 6, 8 , 10] B = [i for i in A] A = 'Hi' print('List A is : % s' % (A)) print('List B is : % s' % (B))
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.