1

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.

Michael
  • 7,407
  • 8
  • 41
  • 84

3 Answers3

3

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]]
Community
  • 1
  • 1
brianpck
  • 8,084
  • 1
  • 22
  • 33
3

You can do it in one line of code:

[[z[i] for z in x] for i in range(len(x[0]))]

What it does is that to iterate over all indexes (i) and then iterate over all lists in x (z) and create a new list.

afsafzal
  • 592
  • 5
  • 15
0

You can try zip

>>> result = zip(a,b,c,d) # This gives ans as list of tuples [(1, 4, 7, -1), (2, 5, 8, -2), (3, 6, 9, -3)]
>>> result_list = [list(elem) for elem in result] #convert list of tuples to list of list
>>> result_list
[[1, 4, 7, -1], [2, 5, 8, -2], [3, 6, 9, -3]]
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61