Python Tutorials

Python Programs

Python Transpose a Matrix


Python Transpose a Matrix

In this tutorial, we will learn how to transpose a matrix in Python. We will cover the basic concept of matrix transposition and implement a function to perform the operation.


What is Matrix Transposition

Matrix transposition is the process of swapping the rows and columns of a matrix. The element at row i and column j of the original matrix becomes the element at row j and column i in the transposed matrix.


Syntax

The syntax to transpose a matrix in Python is:

def transpose_matrix(matrix):
    transposed = []
    for i in range(len(matrix[0])):
        row = []
        for j in range(len(matrix)):
            row.append(matrix[j][i])
        transposed.append(row)
    return transposed


Transposing a matrix

We can create a function to transpose a matrix by swapping its rows and columns.

For example,

  1. Define a function named transpose_matrix that takes one parameter matrix.
  2. Initialize an empty list transposed to store the transposed matrix.
  3. Use a nested for loop to iterate through the elements of the matrix.
  4. In the inner loop, append the element at row j and column i of the original matrix to a new row.
  5. Append the new row to the transposed list.
  6. Return the transposed matrix.
  7. Call the function with a sample matrix and print the result.

Python Program

def transpose_matrix(matrix):
    transposed = []
    for i in range(len(matrix[0])):
        row = []
        for j in range(len(matrix)):
            row.append(matrix[j][i])
        transposed.append(row)
    return transposed

# Sample matrix
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

# Transpose the matrix
result = transpose_matrix(matrix)

# Print the result
print('Transposed matrix is:')
for row in result:
    print(row)

Output

Transposed matrix is:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]