Matrix Transpose in Python Matrix Transpose in Python python python

Matrix Transpose in Python


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')]


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

the list generator creates a new 2d array with list items instead of tuples.


If your rows are not equal you can also use map:

>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]>>> map(None,*uneven)[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]

Edit: In Python 3 the functionality of map changed, itertools.zip_longest can be used instead:
Source: What’s New In Python 3.0

>>> import itertools>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]>>> list(itertools.zip_longest(*uneven))[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]