Reputation: 562
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
?
Upvotes: 0
Views: 66
Reputation: 12807
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.
Upvotes: 1