In the following Python code, I created a list a which contains a number of lists, and then created a copy of it, b, but unlike with lists that do not contain other lists, when b is changed, a also changes accordingly. Can someone explain how to prevent this from happening other than by copying each list separately?
a = [[None, None, None], [None, None, None], [None, None, None]]
b=a[:]
b[0][0] = 5
a
[[5, None, None], [None, None, None], [None, None, None]]
b
is a shallow copy of a
(check out the values id(a[0])
and id(b[0])
, they will be same even if id(a)
!= id(b)
). You need to take care of the elements inside the list as well (if they are mutable and modified, a shallow copy will reflect the changes in both the places). You can do something like this to create a deep
copy:
import copy
b = copy.deepcopy(a)
Read up on shallow and deep copy operations in Python.