Python problem 11 of 30

Transpose a matrix

  • Python
  • Easy

Write transpose(m) that turns the rows of a rectangular list-of-lists into columns.

transpose([[1, 2, 3],
           [4, 5, 6]])
# [[1, 4], [2, 5], [3, 6]]
Show hint

zip(*m) passes each row as a separate argument to zip.

Show solution
def transpose(m):
    return [list(col) for col in zip(*m)]

zip pairs up the first items of every row, then the second items, and so on, which is exactly a column. Each column comes back as a tuple, so list(col) converts it.

Want a problem like this every day? See today's problem and keep a streak going.