29. Transpose a matrix
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
matrix = [[1, 2, 3], [4, 5, 6]][[1, 4], [2, 5], [3, 6]]Example 2
matrix = [[1], [2], [3]][[1, 2, 3]]Example 3
matrix = [[5, 6]][[5], [6]]Constraints
matrixhas 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).
- Column
cof the matrix is the item at indexcof every row:[row[c] for row in matrix]. It becomes rowcof the answer. - There are
len(matrix[0])columns, so loopfor c in range(len(matrix[0])):and collect each column into the result. - An empty matrix has no
matrix[0]: checkif not matrix:and return[]first.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.