Q-bart Q-bart -4 years ago 118
Python Question

How can I use zip(), python

For example, I have these variables

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

If I use 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:


I get:

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

What must I do?

Answer Source

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)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download