1

Updates on a 2-D array seem to work differently depending on how the array is initialized.

t = [[-9]*3]*3
t[0][1] = 5
#[[-9, 5, -9], [-9, 5, -9], [-9, 5, -9]]

This is unexpected since every row is updated (the second column has value 5).

Contrast this to the following:

t = [[-9, -9, -9], [-9, -9, -9], [-9, -9, -9]]
t[0][1] = 5
#[[-9, 5, -9], [-9, -9, -9], [-9, -9, -9]]

This is as expected. What's going on behind the scenes?

yalis
  • 1,508
  • 1
  • 16
  • 24
  • Related: See here for ways to initialize 2-D arrays in python: https://stackoverflow.com/questions/2397141/how-to-initialize-a-two-dimensional-array-in-python – yalis Jan 27 '20 at 16:54

1 Answers1

2

When you use the * operator to repeat a list in Python, it simply creates repeated references to the original list, as opposed to creating multiple independent lists. You can use Python's id function to find the internal identification number for any Python value, which can be used to tell if two similar values are actually distinct or not. For example:

>>> t = [[9]*3]*3
>>> t
[[9, 9, 9], [9, 9, 9], [9, 9, 9]]
>>> id(t[0])
4354326848
>>> id(t[1])
4354326848
>>> id(t[2])
4354326848


>>> t = [[-9, -9, -9], [-9, -9, -9], [-9, -9, -9]]
>>> id(t[0])
4354326912
>>> id(t[1])
4354327616
>>> id(t[2])
4354327168

Observe than in the first case, all three of the id numbers are the same, while in the second case, they are all different.

So, in the first case, you really had three references to the same underlying list, and when you changed an element of one of them, they all changed together (since they were really all one list).

Andrew Merrill
  • 1,672
  • 11
  • 14