2

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 ?

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • Does this answer your question? [How to zip lists in a list](https://stackoverflow.com/questions/4112265/how-to-zip-lists-in-a-list) – Lakshya Srivastava Feb 25 '20 at 19:29
  • this might be useful : https://stackoverflow.com/questions/4112265/how-to-zip-lists-in-a-list – Sajan Feb 25 '20 at 19:29
  • What do you mean by "nuked"? Everything is alright, isnt it? :) – tim Feb 25 '20 at 19:31
  • @tim I clicked on that time-piece icon under the check-mark of one answer and Momentarily _all_ answers disappeared! Freaked me out. I opened this page in a new tab and things were back. What's up with that? – WestCoastProjects Feb 25 '20 at 19:35
  • Not so sure :) You should have rather clicked the "Accept Answer" on mine before this question got closed. But dont worry :) – tim Feb 25 '20 at 19:37
  • 1
    i'm waiting another 10 seconds for min wait to accept your answer. That's why i had clicked on the time-piece: maybe it would tell me how much longer i needed to wait to accept Instead it nuked both answers from my page. – WestCoastProjects Feb 25 '20 at 19:38
  • The same way as if you were calling *anything else* besides `zip`. You have a list of arguments; you want them to be used as separate arguments for the call; that is exactly what `*` does. – Karl Knechtel Aug 29 '22 at 13:33

3 Answers3

4

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]]
tim
  • 9,896
  • 20
  • 81
  • 137
2

This will do the trick:

list(zip(*d))
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
1

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.

bqbastos
  • 74
  • 3