- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Transpose a matrix in Python?

Transpose a matrix means we’re turning its columns into its rows. Let’s understand it by an example what if looks like after the transpose.

Let’s say you have original matrix something like -

x = [[1,2][3,4][5,6]]

In above matrix “x” we have two columns, containing 1, 3, 5 and 2, 4, 6.

So when we transpose above matrix “x”, the columns becomes the rows. So the transposed version of the matrix above would look something like -

x1 = [[1, 3, 5][2, 4, 6]]

So the we have another matrix ‘x1’, which is organized differently with different values in different places.

Below are couple of ways to accomplish this in python -

**Method 1 -** Matrix transpose using Nested Loop -

#Original Matrix x = [[1,2],[3,4],[5,6]] 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)

## Result

[1, 3, 5] [2, 4, 6]

**Method 2 -** Matrix transpose using Nested List Comprehension.

#Original Matrix x = [[1,2],[3,4],[5,6]] result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))] for r in Result print(r)

## Result

[1, 3, 5] [2, 4, 6]

List comprehension allows us to write concise codes and should be used frequently in python.

**Method 3 -** Matrix Transpose using Zip

#Original Matrix x = [[1,2],[3,4],[5,6]] result = map(list, zip(*x)) for r in Result print(r)

## Result

[1, 3, 5] [2, 4, 6]

**Method 4 -** Matrix transpose using numpy library
Numpy library is an array-processing package built to efficiently manipulate large multi-dimensional array.

import numpy #Original Matrix x = [[1,2],[3,4],[5,6]] print(numpy.transpose(x))

## Result

[[1 3 5] [2 4 6]]

- Related Questions & Answers
- How to Transpose a Matrix using Python?
- Transpose a matrix in C#
- Transpose a matrix in Java
- Find the transpose of a matrix in Python Program
- Java program to transpose a matrix.
- How to Transpose a matrix in Single line in Python?
- Python Program to find the transpose of a matrix
- Compute a matrix transpose with Einstein summation convention in Python
- C++ Program to Find Transpose of a Matrix
- Java Program to Find Transpose of a Matrix
- Program to find the transpose of given matrix in Python
- A C++ Program for 2d matrix for taking Transpose
- Java program to print the transpose of a matrix
- C++ Program to Find Transpose of a Graph Matrix
- How to calculate transpose of a matrix using C program?