0

I created an array with two sub-arrays containing zeros:

a=[[0]*3]*2

This looks like so:

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

I try to modify the first value of the first sub-array like this:

a[0][0] = 1

Then the array looks like this:

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

The second sub-array was changed as well. If i create the sub-arrays individually by writing

a=[0]*2
a[0]=[0]*3
a[1]=[0]*3

and then execute the same command to modify the first value, the result looks like this:

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

Why does the array behave differently in these cases and is there a way to change values of sub-arrays when initializing them together?

LukasFun
  • 171
  • 1
  • 4
  • 17
  • this will most likely answer you question: https://stackoverflow.com/q/8056130/10875953 – Robin Dillen Jan 10 '22 at 19:11
  • 1
    `a = [[0] * 3 for _ in range(2)]` – Olvin Roght Jan 10 '22 at 19:12
  • BTW, these are *lists* not arrays, in Python 'array' generally implies a `numpy` array (or even an `array.array`, but that's more esoteric) – juanpa.arrivillaga Jan 10 '22 at 19:13
  • 1
    So the reason is because the sub-arrays (or sub lists, as it were) here are actually the same object? – LukasFun Jan 10 '22 at 19:20
  • Yes - the `*` operator on a list will copy the references in the multiplied list. The docs describe it as "equivalent to adding [the list] to itself n times" and note this common problem in footnote 2 here: https://docs.python.org/3/library/stdtypes.html#common-sequence-operations – Peter DeGlopper Jan 10 '22 at 19:37

0 Answers0