Transpose of a Matrix (One Liner)| Python
Hello everyone, in this tutorial we are going to learn a trick to find the transpose of a matrix of any given dimension with Python. A normal way to do this is by initializing two loops and performing interchange operations inside the loop. But we can do this in one line using the zip function. Let us start by knowing about what is a transpose.
What is Matrix Transpose?
The flipped version of the original matrix is nothing but the transpose of a matrix, this can be done by just interchanging the rows and columns of the matrix irrespective of the dimensions of the matrix. We denote the transpose of matrix A by A^T and the superscript “T” means “transpose”.
So here is the link of the program to find the transpose of a matrix using the swapping technique.
Now let us learn our one line trick.
We can do this by using the involving function in conjunction with the * operator to unzip a list which becomes a transpose of the given matrix.
transpose_matrix = zip(*original_matrix)
So this is how we can implement the Python code for one liner transpose of a matrix.
x = [(31,17,23),(40 ,51,56),(13 ,12,3)] y = list(zip(*x)) print("The original matrix is:") for row in x: print(row) print("The transposed matrix is:") for row in y: print(row)
Now we are ready to run our code and see the corresponding output. below are the given result that our code will return:
The original matrix is: (31, 17, 23) (40, 51, 56) (13, 12, 3) The transposed matrix is: (31, 40, 13) (17, 51, 12) (23, 56, 3)
The original matrix is: (1, 2, 3, 4) (5, 6, 7, 8) (9, 10, 11, 12) The transposed matrix is: (1, 5, 9) (2, 6, 10) (3, 7, 11) (4, 8, 12)
Yay! We did it, this is how we can find the transpose of a matrix of any dimension and we did it in a single line.