Aug 6, 2018

The transpose of a matrix in Python

In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal, that is it switches the row and column indices of the matrix by producing another matrix denoted as AT. It is achieved by any one of the following equivalent actions: reflect A over its main diagonal to obtain AT, write the rows of A as the columns of AT, write the columns of A as the rows of AT. Formally, the i-th row, j-th column element of AT is the j-th row, i-th column element of A: i j = j i

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
The following list comprehension will transpose rows and columns:

>>>
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]