0

I had a confusion where I initialize a 2D array in this way:

>>> a = [[0] * 3] * 3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

while I was expecting it to be

[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

I also tried

>>> a = [[0 for _ in range(3)] for _ in range(3)]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Which worked as expected

Wonder what is the reason caused this?

junhan
  • 119
  • 4
  • 11

1 Answers1

2

With the outter *3 you are making a shallow copy of a list.

This can be easily verifier by printing ids. An id is unique to each item.

a = [[0] * 3] * 3
print(*map(id, a))
# Same ID

Instead, you absolutely need to generate new lists

a = [[0] * 3 for _ in range(3)]
print(*map(id, a))
# Different ids

If you want more information you can check this question : What exactly is the difference between shallow copy, deepcopy and normal assignment operation?

BlueSheepToken
  • 5,751
  • 3
  • 17
  • 42