Python Program to Transpose a Matrix
Beginner · Matrices
The transpose of a matrix is made by turning its rows into columns, so the item in row i, column j moves to row j, column i. A 2 x 3 matrix becomes a 3 x 2 matrix. This program builds the transpose with nested loops.
Program
Original matrix: [1, 2, 3] [4, 5, 6] Transpose: [1, 4] [2, 5] [3, 6]
How it works
- The matrix is a list of rows:
len(matrix)is the number of rows andlen(matrix[0])the number of columns. - The outer loop goes through the columns, because each column of the original becomes a row of the transpose.
- The inner loop collects
matrix[i][j]from every row intonew_row. - Each finished
new_rowis added totranspose, which is printed row by row.
Other ways to write it
Using zip()
Transpose: [1, 4] [2, 5] [3, 6]
zip(*matrix) passes each row to zip(), which groups the first items, then the second items, and so on, which are exactly the columns.
Using a nested list comprehension
Transpose: [1, 4] [2, 5] [3, 6]
This is the nested loop version squeezed into one line: the outer part loops over columns, the inner part over rows.
Try it yourself
Check whether a square matrix is symmetric, meaning it equals its own transpose, using [[1, 2], [2, 1]] as an example.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises