1

I had a confusion where I initialize a 2D array in this way:

>>> a = [[0] * 3] * 3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

while I was expecting it to be

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

I also tried

>>> a = [[0 for _ in range(3)] for _ in range(3)]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Which worked as expected

Wonder what is the reason caused this?

1
  • 2
    Because in the first code, the x3 is making 3 references of the same list Commented Jul 31, 2019 at 6:23

1 Answer 1

2

With the outter *3 you are making a shallow copy of a list.

This can be easily verifier by printing ids. An id is unique to each item.

a = [[0] * 3] * 3
print(*map(id, a))
# Same ID

Instead, you absolutely need to generate new lists

a = [[0] * 3 for _ in range(3)]
print(*map(id, a))
# Different ids

If you want more information you can check this question : What exactly is the difference between shallow copy, deepcopy and normal assignment operation?

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

1 Comment

Always thought they are equivalent, thanks for your answer.

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.