Drill

ProblemsPython › patterns

Turn the rows into columns

easypatternsGridsArraysPython

An export writes a table row by row, and the spreadsheet on the other end wants it the other way round.

transpose(table: list<list<int>>) → list<list<int>>

Solve it in the editor →

Where you start

def transpose(table: list[list[int]]) -> list[list[int]]:
    

Worked examples

CallResult
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

The same problem in another language

More patterns problems in Python