dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Transpose a Matrix in Python

Learn how to use the zip library built into Python to transpose a matrix.


advertisement

One of the inbuilt libraries in Python is zip. It can be utilized to transpose a matrix by performing an Unzip followed by zip as shown below.

The "zip()" function returns an iterator of tuples based on the "iterable" object. In order to get the transpose of the matrix, first, we need to unzip the list using "*"operator then zip it.

inputMatrix = [ [7, 14, 21], [1, 2, 3] ]
zip(*inputMatrix)

Output will be as follows:

[ (7, 1), (14, 2), (21, 3) ]

 

Visit the DevX Tip Bank

 



   
Srinath M. S. says: "I would love to leave a footprint in this flat world."
Thanks for your registration, follow us on our social networks to keep up-to-date