The Wayback Machine - https://web.archive.org/web/20240709221510/https://www.geeksforgeeks.org/transpose-matrix-single-line-python/
Open In App

Transpose a matrix in Single line in Python

Last Updated : 16 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Transpose of a matrix is a task we all can perform very easily in Python (Using a nested loop). But there are some interesting ways to do the same in a single line. In Python, we can implement a matrix as a nested list (a list inside a list). Each element is treated as a row of the matrix. For example m = [[1, 2], [4, 5], [3, 6]] represents a matrix of 3 rows and 2 columns. The first element of the list – m[0] and the element in the first row, first column – m[0][0].

Example

Input: [[1,2],[3,4],[5,6]]
Output: [[1,3,5],[2,4,6]]
Explanation: Suppose we are given a matrix
[[1, 2],
[3, 4],
[5, 6]]
Then the transpose of the given matrix will be,
[[1, 3, 5],
[2, 4, 6]]

Python Programs to Transpose a Matrix in Single Line

There are various approaches to find the Transpose of a matrix in a single line in Python. In this article, we will discuss all the approaches which are specific to transposing a matrix in a single line in Python.

Transpose Matrix In Single Line using List Comprehension

List comprehension is used to iterate through each element in the matrix. In the given example, we iterate through each element of matrix (m) in a column-major manner and assign the result to the rez matrix which is the transpose of m.

Python3




m = [[1, 2], [3, 4], [5, 6]]
for row in m:
    print(row)
rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
print("\n")
for row in rez:
    print(row)


Output:

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

Transpose a matrix in Single line in Python using zip

Python Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. In this example we unzip our array using * and then zip it to get the transpose.

Python3




matrix = [(1, 2, 3), (4, 5, 6),
                  (7, 8, 9), (10, 11, 12)]
for row in matrix:
    print(row)
print("\n")
t_matrix = zip(*matrix)
for row in t_matrix:
    print(row)


Output:

Note :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix)).

(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
(10, 11, 12)
(1, 4, 7, 10)
(2, 5, 8, 11)
(3, 6, 9, 12)

Python Programs to Transpose a matrix using NumPy

Python NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays.

Example 1: The transpose method returns a transposed view of the passed multi-dimensional matrix.

Python3




import numpy
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix)
print("\n")
print(numpy.transpose(matrix))


Output:

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

Example 2: Using “.T” after the variable

Python3




import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
print("\n")
print(matrix.T)


Output:

As you can see that both the output are same.

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

Fastest way to Transpose a Matrix using Itertools

Python itertools is a module that provides various functions that work on iterators to produce complex iterators. chain() is a function that takes a series of iterables and returns one iterable.

In this example, we are using chain() function to convert all the values inside the matrix into a single list and then transpose the matrix. This method is way faster then other methods.

Python3




from itertools import chain
import time
import numpy as np
 
def transpose2(M):
    n = len(M[0])
    L = list(chain(*M))
    return [L[i::n] for i in range(n)]
 
start = time.time_ns()
matrix = np.array([[1, 2, 3], [4, 5, 6]])
end = time.time_ns()
print(transpose2(matrix))
print("Time taken", end-start, "ns")


Output

[[1, 4], [2, 5], [3, 6]]
Time taken 108570 ns


Previous Article
Next Article

Similar Reads

Python | Numpy matrix.transpose()
With the help of Numpy matrix.transpose() method, we can find the transpose of the matrix by using the matrix.transpose()method in Python. Numpy matrix.transpose() Syntax Syntax : matrix.transpose() Parameter: No parameters; transposes the matrix it is called on. Return : Return transposed matrix What is Numpy matrix.transpose()?`numpy.matrix.trans
3 min read
Python | Pandas TimedeltaIndex.transpose()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.transpose() function return the transpose of the given TimedeltaIndex object, which is by definition self. Syntax
2 min read
Python | Pandas Series.transpose()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.transpose() function return the transpose, which is by definition self. Syntax:
2 min read
Python | Numpy numpy.transpose()
With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass
2 min read
Python PIL | Image.transpose() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.transpose() Transp
2 min read
Numpy MaskedArray.transpose() function | Python
numpy.MaskedArray.transpose() function is used to permute the dimensions of an masked array. Syntax : numpy.ma.transpose(axis) Parameters: axis :[list of ints, optional] By default, reverse the dimensions, otherwise permute the axes according to the values given. Return : [ ndarray] Resultant array with its axes permuted.. Code #1 : # Python progra
2 min read
Wand transpose() function - Python
The transpose() function is an inbuilt function in the Python Wand ImageMagick library which is used create a vertical mirror image by reflecting the pixels around the central x-axis. Syntax: transpose() Parameters: This function does not accept any parameter.Return Value: This function returns the Wand ImageMagick object. Original Image: Example 1
2 min read
Python OpenCV – cv2.transpose() method
OpenCV is a library of programming functions mainly aimed at real-time computer vision. cv2.transpose() method is used to transpose a 2D array. The function cv::transpose rotate the image 90 degrees Counter clockwise. Syntax: cv2.cv.transpose( src[, dst] ) Parameters: src: It is the image whose matrix is to be transposed. dst: It is the output imag
1 min read
Transpose Dual Tuple List in Python
Sometimes, while working with Python tuples, we can have a problem in which we need to perform tuple transpose of elements i.e, each column element of dual tuple becomes a row, a 2*N Tuple becomes N * 2 Tuple List. This kind of problem can have possible applications in domains such as web development and day-day programming. Let's discuss certain w
5 min read
Launch an HTTP Server with a Single Line of Python Code
Python, with its built-in capabilities, offers a simple and effective way to do this. With just a single line of code, you can launch an HTTP server to serve files from your local directory. This feature can be incredibly handy for developers, educators, and anyone needing a quick and easy way to share files over a network. Use Cases to Launch An H
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg