0

I am trying to create an empty(only zeros) square matrix in a simple way. The first method that came to my mind is using the * operator:

size = 5
matrix = [[0] * size] * size

When I try to assign some element of it, say, matrix[0][0] = 1 I get such a matrix:

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

I can see that * did not just create a new list but rather copied the reference of the initially created list 5 times. So, in order to make this somewhat presentable, I did the following:

size = 5
matrix = []
for _ in range(size):
    matrix.append([0] * size)
matrix[0][0] = 1
print(matrix)

Now the result is correct:

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

Question: In the first code, when I initialized the matrix with * operator (matrix = [[0] * size] * size) assigning the first element would change all first elements of each row. But then I tried to modify entire row like this: matrix[0] = [1, 0, 0, 0, 0] which gave me the correct result. So what's the true way?

Sakhund
  • 225
  • 1
  • 4
  • 30

0 Answers0