Advanced · 2D lists · 175 of 264
Transpose a matrix
Swap the rows and the columns of a matrix.
Input: r and c, then r lines of c whole numbers. Output: the c by r transposed matrix.
Examples
Input
2 3 1 2 3 4 5 6
Output
1 4 2 5 3 6
Input
1 1 7
Output
7
One more test checks other inputs when you press Check.
Stuck? The idea behind 2d lists
A list of lists is a grid: grid[row][col]. Read one row per line, each turned into numbers.
Loop over rows, then over the columns inside each row. zip(*grid) turns rows into columns.
grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
print(*row)
print(grid[1][2]) # 6Watch for: [[0] * 3] * 2 makes two names for the same row: changing one changes both. Build rows with a comprehension: [[0] * 3 for _ in range(2)].