Home > Mobile >  Proper way to update a list with a function?
Proper way to update a list with a function?

Time:10-27

My following program is not modifying the original list (myMatrix). What is the correct way to fix this problem?

def transpos(matrixx: list):
    newMatrix = [[matrixx[j][i] for j in range(len(matrixx))] for i in range(len(matrixx[0]))]

    myMatrix = newMatrix

myMatrix = [[1, 2], [3, 4]]
transpos(myMatrix)
print(myMatrix)

CodePudding user response:

It's enaugh that you add global myMatrix as below:

def transpos(matrixx: list):
    global myMatrix
    newMatrix = [[matrixx[j][i] for j in range(len(matrixx))] for i in range(len(matrixx[0]))]

    myMatrix = newMatrix

myMatrix = [[1, 2], [3, 4]]
transpos(myMatrix)
print(myMatrix)

CodePudding user response:

Better way to return new list and assign to myMatrix.

    def transpos(matrixx: list):
        newMatrix = [[matrixx[j][i] for j in range(len(matrixx))] for i in range(len(matrixx[0]))]

        return newMatrix

    myMatrix = [[1, 2], [3, 4]]
    myMatrix = transpos(myMatrix)
    print(myMatrix)
  • Related