-2

Changing the value of a variable b, which is a copy of a, also changes the value of a.

a = [[0]]
b = a.copy()

print("a before", a)

b[0][0] = 1

print("a after ", a)

prints:

a before [[0]]
a after  [[1]]

Although this works:

a = [0]
b = a.copy()

print("a before", a)

b[0] = 1

print("a after ", a)

prints:

a before [[0]]
a after  [[0]]
Ants Aus
  • 45
  • 7
  • a copy is only a shallow copy, the "outermost" container was created from scratch, but the items inside are still references. use `from copy import deepcopy` – Paritosh Singh Dec 04 '19 at 15:55
  • Does this answer your question? [Copying nested lists in Python](https://stackoverflow.com/questions/2541865/copying-nested-lists-in-python) – abhilb Dec 04 '19 at 15:55

1 Answers1

1

Turns out copy.deepcopy works.

import copy

a = [[0]]
b = copy.deepcopy(a)

print("a before", a)

b[0][0] = 1

print("a after ", a)

prints:

a before [[0]]
a after  [[0]]
Ants Aus
  • 45
  • 7