The Wayback Machine - https://web.archive.org/web/20240910182547/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
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Multiplication of two Matrices in Single line using Numpy in Python
Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the second matrix. Example: Multiplication of two matr
3 min read
How to find the transpose of a tensor in PyTorch?
In this article, we are going to discuss how to find the transpose of the tensor in PyTorch. The transpose is obtained by changing the rows to columns and columns to rows. we can transpose a tensor by using transpose() method. the below syntax is used to find the transpose of the tensor. Syntax: torch.transpose(input_tens, dim_0, dim_1) Parameters:
2 min read
Pandas DataFrame transpose() Method: Swap Rows and Columns
Pandas DataFrame is a two-dimensional, size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dictionary-like container for the Series objects. This is the primary data structure of the Pandas. Pandas DataFrame transpos
4 min read
Compare two Files line by line in Python
In Python, there are many methods available to this comparison. In this Article, We'll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation. Files in use: file.txt file1.txt Method 1: Using
3 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Learning Ef
7 min read
PyQtGraph - Setting Symbol of Line in Line Graph
In this article we will see how we can set symbols of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A li
3 min read
PyQtGraph - Setting Shadow Pen of Line in Line Graph
In this article, we will see how we can set shadow pen of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, et
3 min read
PyQtGraph - Setting Pen of Line in Line Graph
In this article we will see how we can set pen of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A li
4 min read
PyQtGraph - Setting Alpha Value of Line in Line Graph
In this article we will see how we can set alpha value of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, et
4 min read
PyQtGraph - Clearing the Line in Line Graph
In this article, we will see how we can clear the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line c
3 min read
PyQtGraph - Getting Data Bounds of the Line in Line Graph
In this article we will see how we can get data bounds of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, et
4 min read
PyQtGraph - Getting Data of Line in Line Graph
In this article we will see how we can get data of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A l
3 min read
PyQtGraph - Getting Name of Line in Line Graph
In this article we will see how we can get name of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A l
4 min read
PyQtGraph - Setting Symbol Pen of Line in Line Graph
In this article we will see how we can set symbol pen of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A
4 min read
PyQtGraph - Setting Symbol Size of Line in Line Graph
In this article we will see how we can set symbol size of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.)
4 min read
PyQtGraph - Getting Pixel Padding of Line in Line Graph
In this article we will see how we can get pixel padding of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video,
4 min read
PyQtGraph - Setting Symbol Brush of Line in Line Graph
In this article we will see how we can set symbols brush of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.
3 min read
PyQtGraph - Getting Starting Co-ordinates of Line in Line Graph
In this article, we will see how we get the starting coordinates of the line i.e origin of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for
4 min read
PyQtGraph - Setting X and Y Co-ordinates of Line in Line Graph
In this article, we will see how we can set X & Y coordinates of the line i.e origin of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for
3 min read
PyQtGraph - Getting X and Y Co-ordinates of Line in Line Graph
In this article, we will see how we can get X & Y coordinates of the line i.e origin of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for
4 min read
Article Tags :
Practice Tags :