zip() is a built-in Python function that returns an iterator by aggregating the contents from other iterators. Here’s a simple example where we combine the contents of two tuples, y and z:

>>> y = ('a','b','c','d','e')
>>> z = (1,2,3,4,5)
>>> zip(y,z)
<zip object at 0x10cba6bc8>
# let's use a dict() to see the contents
>>> x = dict(zip(y,z))
>>> x
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Note that if you use zip() to combine iterators of unequal lengths, the trailing, unmatched values will be excluded:

>>> a = dict(zip((1,2,3),('a','b')))
>>> a
{1: 'a', 2: 'b'} # no 3 here!

Fortunately the itertools module provides a function, zip_longest, to use in these situations. By default it will set a trailing, unmatched value to None:

>>> import itertools
>>> ex1 = dict(itertools.zip_longest((1,2,3),('a','b')))
>>> ex1
{1: 'a', 2: 'b', 3: None}

However you can use the optional third parameter to specify a fillvalue:

>>> import itertools
>>> ex2 = dict(itertools.zip_longest((1,2,3),('a','b'),fillvalue='-'))
>>> ex2
{1: 'a', 2: 'b', 3: '-'}




Want to improve your Python? I have a list of recommended Python books.