2
array1=[[0 for rows in range(9)] for cols in range(9)]
array2=list(array1)
array1[0][0]=1
print(array2[0][0])
print(id(array1) is id(array2))

This gives: 1 False

The arrays have separate ID's but nevertheless, changing array1 still changes array2. Why?

  • Does this answer your question? [Copying nested lists in Python](https://stackoverflow.com/questions/2541865/copying-nested-lists-in-python) – stackprotector May 09 '20 at 15:46

2 Answers2

1

list() will only copy the first dimension of your list. But you have a list of lists and the second dimension will still be linked. You can use deepcopy to clone all dimensions of a list:

from copy import deepcopy

array1=[[0 for rows in range(9)] for cols in range(9)]
array2=deepcopy(array1)
array1[0][0]=1
print(array2[0][0])
print(id(array1) is id(array2))

Result:

0
False
stackprotector
  • 10,498
  • 4
  • 35
  • 64
0

Because the sub-array you're changing isn't a copy.

print(id(array1[0]), id(array2[0]))

Also, don't use is for comparing... practically anything but None, True and False.

AKX
  • 152,115
  • 15
  • 115
  • 172