Python – Matrix Transpose

Python – Matrix Transpose

In Python, a Matrix can be represented using a nested list. Lists inside the list are the rows.

Following is a simple example of nested list which could be considered as a 2x3 matrix.

matrixA = [ [2, 8, 4], [3, 1, 5] ]
Run this program ONLINE

The two lists inside matrixA are the rows of the matrix. Number of elements inside a row represent the number of columns.

Also, in Python programming, the indexing start from 0. So, when we specify matrixA[2][4] in the program, that is actually [2+1][4+1] = [3][5], element of third row and fifth column.

In this tutorial, we will learn how to Transpose a Matrix in Python.

Example 1: Python Matrix Transpose using List Comprehension

In this example, we shall take a Matrix defined using Python List, and find its Transpose using List Comprehension.

Python Program

A = [ [2, 1, 3], [3, 1, 5] ]

#transpose of A
B = [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]

print(' A:', A)
print(' B:', B)
Run this program ONLINE

The code for addition of matrices using List Comprehension is very concise.

Output

 A: [[2, 1, 3], [3, 1, 5]]
 B: [[2, 3], [1, 1], [3, 5]]

Example 2: Python Matrix Transpose using For Loop

In this example, we shall take a matrix, represented using Python List and find its transpose by traversing through the elements using for Loop.

Python Program

A = [ [2, 1, 3], [3, 1, 5] ]

#initialize B with size of A transpose
B = [[0 for j in range(len(A))] for i in range(len(A[0]))]

for j in range(len(A)):
    for i in range(len(A[0])):
        B[i][j] = A[j][i]


print(' A:', A)
print(' B:', B)
Run this program ONLINE

Output

 A: [[2, 1, 3], [3, 1, 5]]
 B: [[2, 3], [1, 1], [3, 5]]

This method is only for demonstrating the transpose of a matrix using for loop. List comprehension used in the first example is preferred, as it is concise.

Summary

In this tutorial of Python Examples, we learned how to do Matrix Transpose in Python using For loop and List comprehension, with the help of well detailed examples.