0

I need to initialize a multidimensional array from an integer n.

n = 2

list_1 = [[] for _ in range(n)]
list_2 = [[]] * n

Then I append 2 to the first item in the nD-array as below.

list_1[0].append(2)
list_2[0].append(2)
print('After')
print(list_1) # [[2], []]
print(list_2) # [[2], [2]] Why this happen?

You could find the code here.

I'm new to python. Could anyone explain in-depth why when I use [[]] *n, it will update all child arrays in list_2?

Anh Nhat Tran
  • 561
  • 1
  • 6
  • 18
  • From what I can tell this is because in `list_1` every item is uniquely created but in `list_2` all the items are duplicates of each other. So, whatever happens to one item in `list_2` will happen to the rest. – Guac Dec 21 '20 at 08:54

1 Answers1

1

You can find a comprehensive answer here: Python list confusion

Basically when the array is initialized with *n, it will copy the address of the first element to all the rest.

Viet
  • 12,133
  • 2
  • 15
  • 21