100 XP

29. Transpose a matrix

Advanced lists comprehensions

A matrix is a grid of numbers, written as a list of rows, where every row is a list of the same length. Transposing it swaps its rows and columns: the first column becomes the first row, the second column becomes the second row, and so on.

1 2 3        1 4
4 5 6   β†’    2 5
             3 6

Write a function transpose(matrix) that takes a matrix and returns its transpose as a new list of lists. A matrix of 2 rows with 3 numbers each becomes one of 3 rows with 2 numbers each. If matrix is empty ([]), return an empty list [].

Example 1

Inputmatrix = [[1, 2, 3], [4, 5, 6]]
Output[[1, 4], [2, 5], [3, 6]]
ExplanationThe column 1, 4 becomes the row [1, 4].

Example 2

Inputmatrix = [[1], [2], [3]]
Output[[1, 2, 3]]
ExplanationOne column of 3 becomes one row of 3.

Example 3

Inputmatrix = [[5, 6]]
Output[[5], [6]]
ExplanationOne row of 2 becomes two rows of 1.

Constraints

  • matrix has 0 to 10 rows.
  • Every row has the same number of items, from 1 to 10.
  • The items are whole numbers.

Submit also runs 3 more tests you can't see.

Practises List Comprehensions (lesson 15).

Code
def transpose(matrix):
    """Swap the rows and columns of a matrix.

    matrix: list of lists of int, every row the same
        length; may be empty
    Returns: list of lists of int, the columns as rows
    """
    # Write your code here
    pass