Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to zip to list of lists?

Alright, so I have two lists that look like this

listx = [2, 4, 5, 9, 11]
listy = [3, 5, 9, 12, 14]

Right now, when I do zip, I get this

listz = zip(listx, listy)
listz = [(2,3), (4,5), (5,9), (9, 12), (11,14)]

Is there any way to make this a list of lists instead of an array, like so

listz = [[2,3], [4,5], [5,9], [9,12], [11,14]]

Thanks!

like image 672
Tom Collins Avatar asked Aug 03 '11 17:08

Tom Collins


People also ask

Can you zip a list of lists in Python?

zip() in Python: Get elements from multiple lists. In Python, the built-in function zip() aggregates multiple iterable objects (lists, tuples, etc.). You can iterate multiple lists in the for loop with zip() .

Can you zip multiple lists?

You can pass multiple iterables to the zip function of the same or different types. In the following example, we defined three lists (all are of the same length), but the data type of the items in each list is different. Similarly, we can join more than three iterables using the zip() function the same way.

Can you zip 4 lists Python?

The Python zip() function makes it easy to also zip more than two lists. This works exactly like you'd expect, meaning you just only need to pass in the lists as different arguments. What is this? Here you have learned how to zip three (or more) lists in Python, using the built-in zip() function!

Can I zip three lists?

Python zipping of three lists by using the zip() function with as many inputs iterables required. The length of the resulting tuples will always equal the number of iterables you pass as arguments. This is how we can zip three lists in Python.


1 Answers

You can use a comprehension:

listz = [list(i) for i in zip(listx, listy)]

or generator expression:

listz = (list(i) for i in zip(listx, listy))
like image 52
utdemir Avatar answered Oct 11 '22 16:10

utdemir