Why is my matrix rewriting itself?

Asked

Viewed 41 times

1

I want to create a square matrix of order N (N is read), but when entering the loop, my matrices are rewriting themselves and always assuming the last number I typed.

I tried to change the range, work with indexers, but I was not successful.

ordem_matriz = int(input("Digite a ordem da matriz (max 10): "))

matriz = [[0] * ordem_matriz] * ordem_matriz

for i in range(len(matriz)):
    for j in range(len(matriz)):
        matriz[i][j] = int(input(f"Digite o vetor [{i}][{j}]: "))
        print(matriz) # isto aqui é só para o controle do que está acontecendo

I expected him to fill each matrix, one by one, but he assumes, in this case, in the 3 matrices, the value I typed. In the end they end up rewriting themselves. As noticeable in 1 of making 4 in the last line.

Digite a ordem da matriz (max 10): 3

Digite o vetor [0][0]: 1
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Digite o vetor [0][1]: 2
[[1, 2, 0], [1, 2, 0], [1, 2, 0]]

Digite o vetor [0][2]: 3
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Digite o vetor [1][0]: 4
[[4, 2, 3], [4, 2, 3], [4, 2, 3]]
  • 1

    It seems to me that, for some reason, its vector has as elements references to the same vector. I can’t explain why I had this result (I don’t understand vector multiplications by scalars in Python), but the change in an element of a vector is "felt" by the "other" vectors. If all line vectors point to the same object, the behavior is exactly what is being demonstrated.

  • 1

    @Jeffersonquesado That’s exactly it.

  • @Woss, I was just about to get in touch with you so I could understand why this is happening, but you were quicker

  • I don’t understand why yet. Since matriz[i][j] would not be every time pointing to a vector [0] different?

  • 1

    @Alecsandercamilo doesn’t seem to be, but it is. When you do something like [[0] * 3]*2 you are creating a list with three zeros and repeating that same list twice. Log in, then, matriz[0][0] or matriz[1][0] will be the same element. I explained better in the question I quoted.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.