Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use zip(), python

Tags:

python

For example, I have these variables

a = [1,2]
b = [3,4]

If I use function zip() for it, the result will be:

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

But I have this list:

a = [[1,2], [3,4]]

And, I need to get the same as in the first result: [(1, 3), (2, 4)]. But, when I do:

zip(a)

I get:

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

What must I do?

like image 741
Q-bart Avatar asked Aug 07 '15 07:08

Q-bart


People also ask

What does zip () do in Python?

The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

How do I zip in Python?

Practical Data Science using PythonUse the zipfile module to create a zip archive of a directory. Walk the directory tree using os. walk and add all the files in it recursively.

What is zip function in pandas?

One of the way to create Pandas DataFrame is by using zip() function. You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe. zip() function creates the objects and that can be used to produce single item at a time.


1 Answers

zip expects multiple iterables, so if you pass a single list of lists as parameter, the sublists are just wrapped into tuples with one element each.

You have to use * to unpack the list when you pass it to zip. This way, you effectively pass two lists, instead of one list of lists:

>>> a = [[1,2], [3,4]]
>>> zip(*a)
[(1, 3), (2, 4)]
like image 108
tobias_k Avatar answered Nov 26 '22 20:11

tobias_k