I have a list a and a list b which is (should be) a copy of list a.
a = [[['a'], ['b'], ['c']], [['A'], ['B'], ['C']]]
b = a[:][:]
b[0][1], b[0][2] = b[0][2], b[0][1]
If I now look at a and b I get the following:
a = [[['a'], ['c'], ['b']], [['A'], ['B'], ['C']]]
b = [[['a'], ['c'], ['b']], [['A'], ['B'], ['C']]]
Why does the swap in list b also affects the original list a?
Thank you.
解决方案
b = a[:][:] is just b = (a[:])[:] or a copy of a copy of the original list. The lists inside the original list are still referenced and when you change them it shows in both lists.
You can do
b = [l[:] for l in a] # a new list, consisting of copies each sublist
or
from copy import deepcopy
b = deepcopy(a)