Matrix Transpose in Python

Julio Diaz picture Julio Diaz · Feb 8, 2011 · Viewed 147.3k times · Source

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

Answer

jfs picture jfs · Feb 8, 2011

Python 2:

>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

Python 3:

>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]