Transpose nested list in python

Use zip with * and map:

>>> map(list, zip(*a))
[['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III'],
 ['1', '262', '86', '48', '8', '39', '170', '16', '4'],
 ['1', '56', '84', '362', '33', '82', '296', '40', '3'],
 ['10', '238', '149', '205', '96', '89', '223', '65', '5'],
 ['92', '142', '30', '237', '336', '140', '210', '50', '2']]

Note that map returns a map object in Python 3, so there you would need list(map(list, zip(*a)))

Using a list comprehension with zip(*...), this would work as is in both Python 2 and 3.

[list(x) for x in zip(*a)]

NumPy way:

>>> import numpy as np
>>> np.array(a).T.tolist()
[['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III'],
 ['1', '262', '86', '48', '8', '39', '170', '16', '4'],
 ['1', '56', '84', '362', '33', '82', '296', '40', '3'],
 ['10', '238', '149', '205', '96', '89', '223', '65', '5'],
 ['92', '142', '30', '237', '336', '140', '210', '50', '2']]

Leave a Comment