Q-bart
Q-bart

Reputation: 1591

How can I use zip(), 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?

Upvotes: 5

Views: 2054

Answers (2)

tobias_k
tobias_k

Reputation: 82899

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)]

Upvotes: 13

tobifasc
tobifasc

Reputation: 765

Just call zip differently:

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

Upvotes: 0

Related Questions