Question :
Hello.
I was programming in python and wanted to do the line switching (between the second and third line) of an array using the following code. But I wanted to know why the variable auxLinha
changes value when I modify b[inicio]
def trocaLinhaB(b,inicio,final):
listaAux = b[inicio]
b[inicio] = b[final]
b[final] = listaAux
The original matrix
0 2 3
0 -3 1
2 1 5
But the result was
[[ 0. 2. 3.]
[ 0. -3. 1.]
[ 0. -3. 1.]]
And I expected the
[[ 0. 2. 3.]
[ 2. 1. 5.]
[ 0. -3. 1.]]
Answer :
I believe you are using the numpy library, so the variable listaAux
stores only one view of the array and not the data (and therefore “changes” the value).
When you change the array, you also change the display.
One possible solution to this problem is to store a copy of the data in the listaAux
variable before making the substitution.
The function code looks like this:
def trocaLinhaB(b,inicio,final):
listaAux = b[inicio].copy() # <= aqui: cria uma cópia
b[inicio] = b[final]
b[final] = listaAux