4

I am new on Python i am working on Transpose of matrix but i found it lengthy code any short procedure please!

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

3 Answers 3

7

You need to install numpy in order to import it Numpy transpose returns similar result when
applied on 1D matrix

import numpy  
mymatrix=[[1,2,3],[4,5,6]] 
print(mymatrix) 
print("\n") 
print(numpy.transpose(mymatrix)) 
Sign up to request clarification or add additional context in comments.

Comments

4

Use zip:

mymatrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)] 
myTransposedMatrix = list(zip(*mymatrix))

>>> myTransposedMatrix
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

Comments

4
import numpy as np
matrix = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]] )
print(matrix.T)

without using numpy


Edit: for Both Python2 and Python3

Python3

[*zip(*matrix)]

Python2

zip(*matrix)

2 Comments

elegant alternative without numpy as well, bravo
As a note, this zip solution is valid just for python2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.