[Python] Changing a variable outside a function in python (transposing a matrix)

Discussão em 'Python' iniciado por Stack, Julho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to transpose a matrix in Python. The function should change the original variable. When I've looked up similar problems, they talk about editing the variable 'in place', but when I tried that I had problems that once an element was changed, it would use the new changed element in later steps, so the result wouldn't be a transpose, and would have some elements missing and some doubled.

    So I tried making a copy, copying term by term, and then copying back, and it seemed to work, except it only works inside the function.

    As in, in the code block below, print#1 is correct, but print#2 is not (it's the original matrix). How can I change the original matrix?

    Thanks for any help

    Oh also, trying to do this without importing anything (deepcopy, transpose), as I haven't learnt that yet.

    # Write your solution here
    def transpose(matrix: list):
    newmatrix = []
    for r in range (len(matrix)):
    temp = []
    for c in range (len(matrix)):
    temp.append(matrix[c][r])
    newmatrix.append(temp)
    matrix = []
    for r in range (len(newmatrix)):
    temp = []
    for c in range (len(newmatrix)):
    temp.append(newmatrix[r][c])
    matrix.append(temp)
    print(matrix) #1

    matrix = [[1,2,3],[4,5,6],[7,8,9]]

    transpose (matrix)
    print(matrix) #2

    Continue reading...

Compartilhe esta Página