pythontranspose

Changing a variable outside a function in python (transposing a matrix)


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

Solution

  • When you execute matrix = [], you don't mutate the caller's matrix. That matrix variable is a local variable, and when you assign to it, it is to that local variable: it does not affect the list that was passed as argument.

    You'd need to mutate the original list, avoiding any assignment to the matrix variable.

    Your code could be rewritten making use of list comprehension, but among the shortest changes to your code in order to achieve correct mutation, is to replace this:

    matrix = []
    

    with:

    matrix.clear()
    

    or

    matrix[:] = []
    

    List comprehension

    Not your question, but with list comprehension you don't need an explicit temporary matrix variable, as all this can be done on-the-fly:

    def transpose(matrix: list):
        matrix[:] = [
            [row[col_index] for row in matrix]
            for col_index in range(len(matrix[0]))
        ]