How to Transpose a Matrix using Python?

PythonServer Side ProgrammingProgramming

When rows and columns of a matrix are interchanged, the matrix is said to be transposed. In Python, a matrix is nothing but a list of lists of equal number of items. A matrix of 3 rows and 2 columns is following list object

X = [[12,7],
    [4 ,5],
    [3 ,8]]

Its transposed appearance will have 2 rows and three columns. Using nested loops this can be achieved.

X = [[12,7],
    [4 ,5],
    [3 ,8]]

result = [[0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[j][i] = X[i][j]

for r in result:
   print(r)

The result will be a transposed matrix

[12, 4, 3]
[7, 5, 8]
raja
Published on 06-Mar-2018 09:53:25
Advertisements