Home > Back-end >  value changing in original list after copy
value changing in original list after copy

Time:07-23

After subtraction result and arr1 have same value while printing everything looks good but while printing matrix 2 and difference of matrix have same value

def matrixinput(a,b):
    arr = []
    for i in range(a):
        row = []
        for j in range(b):
            row.append(int(input()))
        arr.append(row)
    return arr
        
def printmatrix(a,b,c):
    print('Matrix 1')
    for i in a:
        for j in i:
            print(j , end = ' ')
        print()
    print('Matrix 2')
    for i in b:
        for j in i:
            print(j , end = ' ')
        print()
    print('Difference of Matrix')
    for x in c:
        for y in x:
            print(y , end = ' ')
        print()
def Subraction(arr1, arr2):
    result = []
    result.extend(arr1)
    for i in range(len(result)):
        for j in range(len(result[i])):
            result[i][j] = arr1[i][j] - arr2[i][j]
    return result
    
a,b = int(input()), int(input())    
A = matrixinput(a,b)
B = matrixinput(a,b)
C = Subraction(A,B)
printmatrix(A,B,C)

CodePudding user response:

Lists are mutable objects:

In [1]: arr1 = [[1,2,3], [4,5,6]]

In [2]: arr2 = []

In [3]: arr2.extend(arr1)

In [4]: arr2[1][0] = "mutation"

In [5]: arr1
Out[5]: [[1, 2, 3], ['mutation', 5, 6]]

In [6]: arr2
Out[6]: [[1, 2, 3], ['mutation', 5, 6]]

In [7]: arr1 == arr2
Out[7]: True


As you can see, they both will be mutated when you make a change to either arr1 or arr2.

In your case, you are not supposed to extend the arr2 with a mutable list. You should do something like this:

def Subraction(arr1, arr2):
    result = []
    for i in range(len(arr1)):
        result.append([])
        for j in range(len(arr1[i])):
            result[i].append(arr1[i][j] - arr2[i][j])
    return result

CodePudding user response:

Adding to Mohammad Jafari's answer, if you would like to make your original logic work, you should use deepcopy:

import copy
...

def Subraction(arr1, arr2):
    result = []
    result.extend(copy.deepcopy(arr1))
...

See this thread for more details:

How do I clone a list so that it doesn't change unexpectedly after assignment?

  • Related