Python: In place transpose of a matrix

Solution 1:

Option 1: If it's a square matrix NxN then:

def transpose(matrix):
    # Transpose O(N*N)
    size = len(matrix)
    for i in range(size):
        for j in range(i+1, size):
            matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i]

Option 2: universal "pytonic" way is to do it like this:

mat = [[1,2,3],[4,5,6],[7,8,9]]
transpose = list(zip(*mat))
transpose
>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

zip function reference

Solution 2:

For the second loop, change to the following. In your code, you are going into an infinite loop.

    for row in matrix: 
        while len(row)!=row_num:
            if len(row)<row_num:
                row.append(0)
            else:
                row.pop()