0

I made a list of lists and then a copy of it. I tried to insert different values into the elements of each one.

list1 = [
    [0, 0, 0],
    [0, 0, 1],
    [0, 1, 0],
    [0, 1, 1],
    [1, 0, 0],
    [1, 0, 1],
    [1, 1, 0],
    [1, 1, 1]
]

list2 = list1.copy()

for i in range(8):
    list1[i].insert(0, 0)
    list2[i].insert(0, 1)

But the result is both lists affected by both insertions. I know they're different objects because I printed their ID's using id(list1) and id(list2), so I can't understand why this is happening. Any help would be useful.

Thank you in advance.

  • Because both lists *contain the same lists*. You never copied the lists *inside* the list. You want `list2 = [sublist.copy() for sublist in list1]` – juanpa.arrivillaga Jun 08 '21 at 21:39
  • @juanpa.arrivillaga what about [**`deepcopy`**](https://docs.python.org/3/library/copy.html#copy.deepcopy)? – Peter Wood Jun 08 '21 at 21:40
  • 1
    @PeterWood personally I'm not a fan since it's so slow, but it's a very valid solution. Although, there is a subtle difference, `x = []; y = [x, x]; z = copy.deepcopy(y); z[0].append('foo')` will still result in `[['foo'], ['foo']]`, whereas the above will not... – juanpa.arrivillaga Jun 08 '21 at 21:40
  • @juanpa.arrivillaga I must admit I don't trust `deepcopy` for general use, but in this case it's clear what the result would be. – Peter Wood Jun 08 '21 at 21:42
  • 1
    @PeterWood see my edit for a subtle difference. And again, it may be silly, but I just don't like how much extra work it is doing. – juanpa.arrivillaga Jun 08 '21 at 21:43
  • @juanpa.arrivillaga agreed. – Peter Wood Jun 08 '21 at 21:45

1 Answers1

0

Use deepcopy.

from copy import deepcopy
list1 = [
    [0, 0, 0],
    [0, 0, 1],
    [0, 1, 0],
    [0, 1, 1],
    [1, 0, 0],
    [1, 0, 1],
    [1, 1, 0],
    [1, 1, 1]
]

list2 = deepcopy(list1)
for i in range(8):
    list1[i].insert(0, 0)
    list2[i].insert(0, 1)

output

list1: [[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1]]
list2: [[1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44