titus titus - 21 days ago 5
Python Question

Transpose list of lists

Let's take:

l = [[1,2,3],[4,5,6],[7,8,9]]


The result I'm looking for is

r = [[1,4,7],[2,5,8],[3,6,9]]


and not

r = [(1,4,7),(2,5,8),(3,6,9)]


Much appreciated

Answer

How about

map(list, zip(*l))
--> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

For python 3.X users do

list(map(list, zip(*l)))