How to use zip (), python

For example, I have these variables

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

If I use the zip() function 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 this:

 zip(a) 

I get:

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

What should I do?

+5
source share
2 answers

zip expects several iterations, so if you pass a single list of lists as a parameter, sublisters simply wrap themselves in tuples with one each element.

You must use * to unzip the list when you pass it to zip . This way you are actually passing two lists instead of a single list of lists:

 >>> a = [[1,2], [3,4]] >>> zip(*a) [(1, 3), (2, 4)] 
+12
source

Just call zip in a different way:

 a = [[1,2], [3,4]] zip(a[0], a[1]) 
0
source

All Articles