Simple Python Tricks 8
In this section you will find simple python tricks
Iterable Python Tricks 2
In this section you will find iterable python tricks
Transpose 2D Array
In this trick, you will know how we can Transpose of Two-Dimensional Array.
Transpose of the matrix means changing the rows of a 2D array into columns and columns into rows.
For Example, we have a matrix of 3 rows and 3 columns
Each element is treated as a row of the matrix.
[1,2,3] martix= [4,5,6] [7,8,9]
Transpose of matrix
[1,4,7] [matrix]T= [2,5,8] [3,6,9]
Now we will use the built-in function zip() to transpose a 2D matrix, it will return an iterator of tuples.we unzip our matrix using * and then zip to get the transpose.
zip(*matrix) <zip object at 0x00D93B48>
Now we will convert this object into List form
list(zip(*matrix)) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]