-3

Basically, this is what I've got:

In [1]: list1 = [[0, 0, 0, 0]] * 10

In [2]: list1
Out[2]: 
[[0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0]]

In [3]: list1[0][1] = 9

In [4]: list1
Out[4]: 
[[0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0],
 [0, 9, 0, 0]]

When trying to change the second element of the first list to 9, I somehow changed all first elements to 9. How did this happen?

Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25

1 Answers1

0

This is shallow copy, just copy reference. Try list1 = [[0, 0, 0, 0] for _ in range(10)]

BugKiller
  • 1,470
  • 1
  • 13
  • 22