Skip to content Skip to sidebar Skip to footer

Python: Swap List Elements In A Copied List Without Affecting The Original List

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 loo

Solution 1:

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 copyimport deepcopy
b = deepcopy(a)

Solution 2:

import copy

a = [[['a'], ['b'], ['c']], [['A'], ['B'], ['C']]]
b = copy.deepcopy(a)
b[0][1], b[0][2] = b[0][2], b[0][1]
print a, b

Post a Comment for "Python: Swap List Elements In A Copied List Without Affecting The Original List"