# The voodoo of zip(*someList)

David Wilson dw at botanicus.net
Mon Aug 30 10:27:01 CEST 2004

```Message Drop Box wrote:

>All,
>
>How (and why) does zip(*someList) work?
>
>
>
>>>>s = [[1, 2, 3], ['one', 'two', 'three'], ['I', 'II', 'III']]
>>>>zip(*s)
>>>>
>>>>
>[(1, 'one', 'I'), (2, 'two', 'II'), (3, 'three', 'III')]
>
>I've never seen the star '*' outside of function/method definitions
>and I've looked in the Python documentation without success. This
>syntax is voodoo to me at the moment. I'm stumped.
>
>Thanks,
>Stuart
>
>
Help on built-in function zip:

zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences.  The returned list is truncated
in length to the length of the shortest argument sequence.

On the asterisk syntax:
http://docs.python.org/tut/node6.html#SECTION006730000000000000000
http://docs.python.org/ref/calls.html

Basically,

your_sequence = [ 1, 2, 3, 4 ]
zip(*your_sequence)

is equivalent to:

zip(1, 2, 3, 4)

In other words, it allows you to programmatically build an argument
list. Similarly,

your_mapping = { 'cmpfunc': lambda x: x }
some_list = [ 3, 1, 6, 2 ]
some_list.sort(**your_mapping)

is equivalent to:

zip(cmpfunc = lambda x: x)

The zip function takes an item from each of the sequences given as
arguments, and packs them into a tuple, continuing until the sequences
are exhausted.

seq1 = [ 1, 2, 3, 4 ]
seq2 = [ 4, 3, 2, 1 ]
seq3 = "dave"

zip(seq1, seq2) is:
[ (1, 4),  (2, 3),  (3, 2),  (4, 1) ]

zip(seq1, seq2, seq3) is:
[ (1, 4, "d"),  (2, 3, "a"),  (3, 2, "v"),  (4, 1, "e") ]

There is also an itertools.izip which does the same thing in a
generator. HTH,

David.

```