How to zip the elements of a single nested list

Question:

Consider a nested list:

d = [[1,2,3],[4,5,6]]                                                                                                                                                                                                                                                  

I want to zip its elements for this result:

 [[1,4],[2,5],[3,6]]

How to do that? An incorrect approach is

list(zip(d))

But that gives:

[([1, 2, 3],), ([4, 5, 6],)]

What is the correct way to do the zip ?

Asked By: WestCoastProjects

||

Answers:

You need to give the single sub-lists via unpacking (*) as single arguments to zip() like this:

d = [[1,2,3],[4,5,6]]          
zip(*d)  # You need this one
[(1, 4), (2, 5), (3, 6)]

This even works for longer lists, in case this is the behaviour you want:

zip(*[[1,2,3],[4,5,6],[7,8,9]])
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want to have a list of lists instead of a list of tuples, just do this:

map(list, zip(*d))
[[1, 4], [2, 5], [3, 6]]
Answered By: tim

This will do the trick:

list(zip(*d))
Answered By: Grzegorz Skibinski

you should unpack d before zipping it:

list(zip(*d))

The output is a list of tuples, as follows:

[(1, 4), (2, 5), (3, 6)]

I hope this fits you well.

Answered By: bqbastos
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.