Editor

Transpose a Matrix

#264 · Python idioms · Intermediate · 55 XP · about 7 min

A matrix is stored as a list of rows, all of the same length. Its transpose swaps rows and columns: the first column becomes the first row, the second column becomes the second row, and so on. A matrix with 2 rows and 3 columns turns into one with 3 rows and 2 columns.

Write transpose(matrix) that returns the transpose as a new list of lists, without changing matrix. If matrix is empty, return an empty list.

Examples

transpose([[1, 2, 3],
           [4, 5, 6]])   # returns [[1, 4], [2, 5], [3, 6]]
transpose([[1, 2, 3]])   # returns [[1], [2], [3]]
transpose([['a', 'b'],
           ['c', 'd']])  # returns [['a', 'c'], ['b', 'd']]

Constraints

  • 0 <= len(matrix) <= 500, and every row has the same length, from 1 to 500
  • The values can be anything: numbers, strings and so on

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.