3

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
2
  • 1
    you could use return matrix instead of print(matrix) and later matrix = transpose(matrix) Commented Jul 20 at 12:16
  • With no other context, this looks like it should be using Numpy instead of bare lists. Commented Jul 20 at 15:24

1 Answer 1

5

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]))
    ]
Sign up to request clarification or add additional context in comments.

2 Comments

That's great, thank you
Or simply matrix[:] = [list(col) for col in zip(*matrix)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.