My following program doesn't modify the original value of the variable myMatrix
:
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)
What is the correct way to fix this problem?
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)