0

I am fairly new to Python and I am trying to write a very simple piece of code. I have defined two matrices (lists of lists), A and B and a function that replaces the columns of matrix A with the columns of Matrix B based on some indicator variable called index. I have also added some print statements for debugging.

A = [[5,-5,5],[7,7,7],[-6,-6,6]]
B = [[2,2,-1],[-1,2,4],[0,-4,3]]
index = [1,2]

def Matrix_Interchange(A,B,index):
    print("Value of A Inputed",A)
    Temp = A
    for i in index:
        Temp[i-1][:]=B[i-1][:]
        print("Value of A in For Loop",A)
    return(Temp)

Matrix_Interchange(A,B,index)
print(A)

The problem I am having is that once the code enters the for loop inside of the function, it is changing the values of the matrix A. Why would it do that if I am no longer referencing A and instead referencing the new matrix Temp?

Here is the output of the print statements I included to help me debug. Am I missing something obvious here?

Value of A Inputed [[5, -5, 5], [7, 7, 7], [-6, -6, 6]]
Value of A in For Loop [[2, 2, -1], [7, 7, 7], [-6, -6, 6]]
Value of A in For Loop [[2, 2, -1], [-1, 2, 4], [-6, -6, 6]]
smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    [Variable assignment and modification (in python)](//stackoverflow.com/q/6793872) – 001 Apr 30 '18 at 21:47
  • 2
    _"the new matrix Temp"_ It's not a new matrix. It's the same matrix. An assignment doesn't make a copy. You'll need to do `Temp = copy.deepcopy(A)`. – Aran-Fey Apr 30 '18 at 21:48

0 Answers0