0

I was trying to initialize a matrix in Python. I did this:

matrix = [[0] * 9] * 9
matrix[0][0] = 1
print(matrix[1][0])

This outputs 1.

Can someone explain why this happens and how [[0] * 9] * 9 works.

My guess is that all the vectors are pointers to the same vector instead of to different vectors, but I don't know why that happens and why [0] * 9 doesn't have the same issue.

Tgb03
  • 1
  • 2
    Your problem is exactly the same as the one in the dupe; the answers explain the cause fairly well. Don't feel bad; this bites every new Python programmer sooner or later. – ShadowRanger Jun 07 '22 at 17:56
  • You can also refer to https://stackoverflow.com/questions/72501577/when-does-list-multiplication-create-multiple-copies-of-the-object-and-when-does/72501627#72501627 – Mechanic Pig Jun 08 '22 at 00:04

0 Answers0