Turn the rows into columns
An export writes a table row by row, and the spreadsheet on the other end wants it the other way round.
- Every row has the same length.
- The value at row r, column c ends up at row c, column r.
- An empty grid comes back empty.
transpose(table: list<list<int>>) → list<list<int>>
Where you start
def transpose(table: list[list[int]]) -> list[list[int]]:
Worked examples
| Call | Result |
|---|---|
transpose([[1, 2, 3], [4, 5, 6]]) | [[1, 4], [2, 5], [3, 6]] |
transpose([[1]]) | [[1]] |
transpose([]) | [] |
transpose([[1, 2], [3, 4]]) | [[1, 3], [2, 4]] |
Hint
The result has one row per original column. Walk the columns on the outside and the rows on the inside.
Reference solution in Python
def transpose(table: list[list[int]]) -> list[list[int]]:
if not table:
return []
flipped = []
for c in range(len(table[0])):
flipped.append([table[r][c] for r in range(len(table))])
return flipped