I want to copy a 2D list, so that if I modify one list, the other is not modified.
For a one-dimensional list, I just do this:
a = [1, 2]
b = a[:]
And now if I modify b, a is not modified.
But this doesn't work for a two-dimensional list:
a = [[1, 2],[3, 4]]
b = a[:]
If I modify b, a gets modified as well.
How do I fix this?
numpy. - Mike Grahamb = a[:], you create a new listb, so for examplea.append([5, 6])will not modifyb, as it just changesa. However, the linea[1][0] = 5will changebbecause it changes a list thatbrefers to. - Artemisa = b.copy(),abecomes a separate place in memory: neither reference nor pointer tob, i.e. it's an independent variable. However, if you doa = b.copy()andbis an array, that does not work. how may there be any logical explanation for that? ifbis an array,a = b.copy()MUST create an independent variable. otherwise it's a bug. p.s. no intention to be rude, pls explain to me if I am wrong - Serhiiawitha = [[1, 2], [3, 4]]. Then you create a copy ofa:b = a.copy. This is a different list, but it contains the same 'sub-lists' this means that changingb, for exampleb.append([5, 6])will not changea, however changing a list inb, for exampleb[0].append(3)will also change the first list ofa. - Artemis