Start learning free

LESSON 331 OF 673 · MATRIX

Transpose Matrix in Python: Swapping Rows and Columns

Practice O(m · n) Read the full explanation

You get a grid matrix of integers, with m rows and n columns.

Return its transpose, a new grid with n rows and m columns.

Row 0 of matrix becomes column 0 of the transpose. Row 1 becomes column 1, and so on.

So the value in row i, column j moves to row j, column i.

matrix is a list of rows. Each row is a list of integers. Row 0 is the top row. Return the transpose as a list of rows too.

 

Example 1:

Input: matrix = [
  [6, 0, -3],
  [2, 9, 4]
]
Output: [
  [6, 2],
  [0, 9],
  [-3, 4]
]
Explanation: The top row (6, 0, -3) is now the left column.
The bottom row (2, 9, 4) is now the right column.
2 rows of 3 values became 3 rows of 2.

Example 2:

Input: matrix = [
  [7],
  [-1],
  [5],
  [10]
]
Output: [
  [7, -1, 5, 10]
]
Explanation: The only column turns into the only row.

Example 3:

Input: matrix = [
  [4, -7],
  [2, 0]
]
Output: [
  [4, 2],
  [-7, 0]
]
Explanation: 4 is in row 0, column 0, so it stays put.
0 is in row 1, column 1, so it stays put too.
-7 and 2 trade places.

 

Constraints:

  • m and n are each from 1 to 500.
  • Each value is an integer from -109 to 109.
  • Negative values and repeats are allowed.

Note:

Your solution should run in O(m * n) time.

STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · MATRIX

    Transpose Matrix in Python, explained

    Problem overview

    The function transpose receives matrix, a list of m rows with n integers each. It returns a new grid with n rows and m columns in which the value at row i, column j of the input sits at row j, column i. Row 0 becomes column 0, row 1 becomes column 1, and so on.

    For [[6, 0, -3], [2, 9, 4]] (2 rows of 3) the result is [[6, 2], [0, 9], [-3, 4]] (3 rows of 2). A single column such as [[7], [-1], [5], [10]] turns into the single row [[7, -1, 5, 10]]. The statement asks for O(m * n) time, which means every value is touched a constant number of times.

    Approach: build the answer cell by cell

    The rule "matrix[i][j] goes to result[j][i]" is the whole algorithm. Visit every cell of the input once and copy it to its mirrored position. What needs a little care is the shape: when the input has m rows and n columns, the output has n rows of m values, so the output must exist, with the right size, before any copying starts.

    A square matrix could be transposed in place by swapping matrix[i][j] with matrix[j][i]. A rectangular one can't, because the result has a different shape from the input. That is why the lesson builds a new grid.

    Step by step

    1. Read the sizes. m = len(matrix) is the number of rows. n = len(matrix[0]) is the number of columns, which is the length of any row, so the first one will do. The constraints guarantee at least one row.
    2. Create result with n rows of m zeros. The shape is swapped on purpose: each column of the input becomes a row of the output, and a column has m values.
    3. Loop over j in range(n). Row j of the result will hold column j of the input, so the outer loop walks over the input's columns.
    4. Loop over i in range(m) inside it. For a fixed column j, i walks down that column from the top row to the bottom row.
    5. Copy one value: result[j][i] = matrix[i][j]. The two indexes trade places, and that exchange is the transpose.
    6. Return result after both loops are done.

    The solution in Python

    class Solution:
        def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
            m = len(matrix)
            n = len(matrix[0])
            result = [[0] * m for _ in range(n)]
            for j in range(n):
                for i in range(m):
                    result[j][i] = matrix[i][j]
            return result
    

    Why the grid is built with a list comprehension

    The expression [0] * m makes one list of m zeros. Putting it inside [... for _ in range(n)] runs it n times, so every row is a separate list. The tempting shortcut [[0] * m] * n repeats a reference to one and the same row n times. Writing into one row then shows up in all of them:

    bad = [[0] * 2] * 3
    bad[0][0] = 9
    print(bad)
    
    [[9, 0], [9, 0], [9, 0]]
    

    The name _ is only a convention for a loop variable that the body doesn't use.

    Rows of a rectangle

    The loop bounds do the shape work: j stops at n and i stops at m. If you swap them by mistake on a non-square grid, you get an IndexError from one of the two lists. On a square grid the mistake goes unnoticed, so test with a rectangle.

    Complexity

    Time is O(m * n): two nested loops, n passes of m assignments, plus the same number of zeros written while creating result. Space is O(m * n) for the returned grid, and the function needs nothing beyond that apart from a few variables.

    Another way

    Python can transpose with zip(*matrix). The star unpacks the rows into separate arguments, and zip then pairs up the first values, the second values, and so on, which gives the columns as tuples:

    matrix = [[6, 0, -3], [2, 9, 4]]
    print(list(zip(*matrix)))
    print([list(row) for row in zip(*matrix)])
    
    [(6, 2), (0, 9), (-3, 4)]
    [[6, 2], [0, 9], [-3, 4]]
    

    The tuples have to be converted back to lists, because the lesson wants a list of lists. The explicit loops teach the indexing that matrix problems keep needing, so they are the better exercise.

    Edge cases and testing

    • A single value, [[5]], comes back as [[5]].
    • A single row of n values becomes n rows of one value; a single column becomes one row.
    • A square matrix such as [[4, -7], [2, 0]] gives [[4, 2], [-7, 0]]: the diagonal stays put and the other two values trade places.
    • Negative numbers and repeats need no special handling, since values are only copied, never compared.

    The two mistakes to avoid are sizing result as m rows of n (the shape of the input, not the output) and reusing one row object for every row of the result.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free