Skip to content
Advertisement

Python Function is returning none although there is the original Value instead of copy

I have a code where I zero a column or row if it contains zero , I have my own function but when I use it it returns None , I made a copy of my matrix and performed changes on it and then I converted the values to the original one and yet I still get no return . my function shouldn’t return values only update the matrix values. here’s the code:

def ConvertMatrix(NumOfRows,M):
    for i in range(numOfRows):
        Col=len(M[i])
    M1=[[M[i][j] for j in range(Col)] for i in range(numOfRows)]
    for i in range(numOfRows):
    for j in range(Col):
        if M[i][j]==0:
            for n in range(Col):
                M1[i][n]=0                   
            for k in range(numOfRows):
                M1[k][j]=0                   
    M=[[M1[i][j] for j in range(Col)] for i in range(numOfRows)]

numOfRows = int(input())
M = [[int(item) for item in input().split(' ')] for i in range(numOfRows)]
M=ConvertMatrix(numOfRows,M)
print(M)

Advertisement

Answer

ConvertMatrix(numOfRows, M) does not return anything which means it implicitly returns None. Hence

M = ConvertMatrix(numOfRows, M)

turns M into None. There are two changes you should apply in order to make this mutation function approach work:

Change the last line in the function to:

M[:] = [[M1[i][j] for ...]  
# slice assignment mutates the passed list object ...
# otherwise you are just rebinding a local variable

Do not assign the function result:

# ...
ConvertMatrix(numOfRows, M)
print(M)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement