Michael Michael - 2 months ago 7
Python Question

Join "colums" of list of lists into "rows" of list of lists

Suppose I have several lists of length n:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
d = [-1, -2, -3]


I put those lists into a list:

x = [a, b, c]


Now I'd like to end up with the following list:

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


What is a quick and pythonic way to do so? (To get from
x
to
y
.)

The entries could be anything, I use numbers just because they visualize good.

Answer

There is a very simple and pythonic way to "reverse-zip" a list in this way. Simple use the zip function and the unpacking operator *:

>>> y = zip(*x)
>>> list(y)
[(1, 4, 7, -1), (2, 5, 8, -2), (3, 6, 9, -3)]

For more information about what is going on, see What is the inverse function of zip in python?

If it is important that it be a list of lists, instead of a list of tuples, you can do the following:

>>> [list(i) for i in zip(*x)]
[[1, 4, 7, -1], [2, 5, 8, -2], [3, 6, 9, -3]]