Python - itertools Module - zip

zip is very useful function that itertools module has to offer along with some important ones like map and chain. Zip combines items of several iterators to produce a tuple.

# itertools_zip.py
for i in zip([1, 2, 3], ['a', 'b', 'c']):

This is very useful when we just want to map items without having a key of sorts.

$ python3 itertools_zip.py

(1, 'a')
(2, 'b')
(3, 'c')

itertools also offers zip_longest which runs till the longest iterator is exhaused.

# itertools_zip_longest.py
from itertools import *

r1 = range(3)
r2 = range(2)

print('zip stops early:')
print(list(zip(r1, r2)))

r1 = range(3)
r2 = range(2)

print('\nzip_longest processes all of the values:')
print(list(zip_longest(r1, r2)))

By default, value for missing item is None but can be changed using the optional argument - fillvalue

$ python3 itertools_zip_longest.py

zip stops early:
[(0, 0), (1, 1)]

zip_longest processes all of the values:
[(0, 0), (1, 1), (2, None)]

This is part of series of articles from Python Module of the Week


- 1 toast