Search notes:

Python: zip

The built-in function zip has nothing to do with zip files. Rather, it creates an iterator from a set of other iterators. The created iterator emits tuples when it is iterated over. The elements of the n-nth tuple correspond to the n-th element in the input-iterators.
numbers = [ 1   ,  2   ,  3     ,  4    ,  5    ]
letters = ['a'  , 'b'  , 'c'    , 'd'   , 'e'   ]
words   = ['one', 'two', 'three', 'four', 'five']

zipped = zip(numbers, letters, words)
for triple in zipped:
    print(triple)
#
# (1, 'a', 'one')
# (2, 'b', 'two')
# (3, 'c', 'three')
# (4, 'd', 'four')
# (5, 'e', 'five')
Github repository about-python, path: /builtin-functions/zip/3-lists.py

Unequal length of «input» iterators

If the «input»-iterators provide an unequal number of elements, the zip() function just stops after finishing the shortest iterator:
numbers = [ 1   ,  2   ,  3                     ]
letters = ['a'  , 'b'  , 'c'    , 'd'   , 'e'   ]
words   = ['one', 'two', 'three', 'four'        ]

zipped = zip(numbers, letters, words)
for triple in zipped:
    print(triple)
#
# (1, 'a', 'one')
# (2, 'b', 'two')
# (3, 'c', 'three')
Github repository about-python, path: /builtin-functions/zip/unequal.py

Unzipping

Note the star (aka unpack) operator .
pairs = [ (1, 'one'  ),
          (2, 'two'  ),
          (3, 'three')
        ]

nums, words = zip(*pairs)

print(nums )
# (1, 2, 3)

print(words)
# ('one', 'two', 'three')
Github repository about-python, path: /builtin-functions/zip/unzip.py

Transposing a matrix

numbers = [ ( 'one' , 'two' , 'three'),
            ( 'eins', 'zwei', 'drei' ),
            ( 'un'  , 'dos' , 'tres' )
          ]

transposed = list(zip(*numbers))

print(transposed)
#
#  [('one', 'eins', 'un'), ('two', 'zwei', 'dos'), ('three', 'drei', 'tres')]
Github repository about-python, path: /builtin-functions/zip/transpose.py
Compare with transposing a matrix with list comprehension.

See also

Using the for statemet to iterate over multiple lists in parallel.
Python: Built in functions
The shell command paste

Index