0
a = [[1], [2, 3], [4, 5, 6]]
b = a[:]

a[0] = "x"
a[1][0] = 10
print(a)
print(b)

Why the result is (--why 10 changed the original object?)

['x', [10, 3], [4, 5, 6]]

[[1], [10, 3], [4, 5, 6]]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    Because, `a[:]` creates a *shallow copy*. The objects inside the new list *are the same as the objects the list was copied from*. `a[1][0] = 10` **changes the list that is being referred to by both objects** – juanpa.arrivillaga Oct 26 '20 at 22:32
  • So, in this case, you would want something like `b = [sub[:] for sub in a]` – juanpa.arrivillaga Oct 26 '20 at 22:35
  • …or you could use `b = copy.deepcopy(a)`. See the `copy` module's [documentation](https://docs.python.org/3/library/copy.html#copy.deepcopy). – martineau Oct 26 '20 at 23:42

0 Answers0