Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I am trying to create a matrix transpose function for python but I can't seem to make it work. Say I have

theArray = [['a','b','c'],['d','e','f'],['g','h','i']]

and I want my function to come up with

newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]

So in other words, if I were to print this 2D array as columns and rows I would like the rows to turn into columns and columns into rows.

I made this so far but it doesn't work

def matrixTranspose(anArray): 

transposed = [None]*len(anArray[0]) 

for t in range(len(anArray)): 

for tt in range(len(anArray[t])): 

transposed[t] = [None]*len(anArray) 

transposed[t][tt] = anArray[tt][t] 

print transposed

1 Answer

0 votes
by (106k points)

You can use the below-mentioned code to transpose a matrix in Python:-

>>> [*zip(*theArray)] 

[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

Related questions

0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
asked Jul 6, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 29, 2019 in Python by Rajesh Malhotra (19.9k points)
0 votes
4 answers

Browse Categories

...