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?

1
  • 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. Commented Dec 21, 2020 at 8:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.