# The matrix transpose by list comprehension

Consider a $3\times 3$ matrix represented by a list of lists:

M = [[1,2,3],
[4,5,6],
[7,8,9]]


Without using list comprehension, the transpose of this matrix could be built up by looping over the rows and columns:

MT = [[0,0,0], [0,0,0], [0,0,0]]
for ir in range(3):
for ic in range(3):
MT[ic][ir] = M[ir][ic]


With one list comprehension, the transpose can be constructed as

MT = []
for i in range(3):
MT.append([row[i] for row in M])


where rows of the transposed matrix are built from the columns (indexed with i=0,1,2) of each row in turn from M). The outer loop here can be expressed as a list comprehension of its own:

MT = [[row[i] for row in M] for i in range(3)]


Note, however, that NumPy provides much easier to use methods for manipulating matrices - see Section 6.6 of the book.