Python - How to Use the Zip Function zip()

Published on Nov. 16, 2017, 4:45 a.m.

Have you ever had the need to iterate over two or more equal-sized lists?

Let's say you have two lists:

>>> cats = ['Koko', 'Gracie', 'Cheshire']
>>> foods = ['dry cat food', 'raw chicken', 'wet cat food']

We can then iterate over them like so:

>>> for c, f in zip(cats, foods):
...     print(f'{c} gets {f}')
Koko gets dry cat food
Gracie gets raw chicken
Cheshire gets wet cat food

Note that this also works with more than 2 lists also:

>>> descriptions = ['black and white cat', 'gray cat', 'leopard-looking cat']
>>> for c, d, f in zip(cats, descriptions, foods):
...     print(f'{c} (the {d}) gets {f}')
Koko (the black and white cat) gets dry cat food
Gracie (the gray cat) gets raw chicken
Cheshire (the leopard-looking cat) gets wet cat food

Now, be aware that while you can use this with dissimilar sized lists, it will take the intersection of the lists like so:

>>> woods = ['pecan', 'hickory', 'cherry']
>>> meats = ['fish', 'pork', 'chicken', 'beef']
>>> for w, m in zip(woods, meats):
...     print(f'smoked {w} for {m}')
smoked pecan for fish
smoked hickory for pork
smoked cherry for chicken

Although beef does well with smoked hickory (and most any other wood), it won't get printed here as the zip forces the equal-sized lists and omits any element that doesn't fit.


A commenter named Dave Mayo brought zip_longest() to my attention. The zip_longest function in the itertools package will allow your iteration to go through the longest list and set None as the value for the shorter list's element. This works the same as zip really but just makes sure that all values in each list are iterated over. Let's use the same example but with zip_longest:

from itertools import zip_longest

woods = ['pecan', 'hickory', 'cherry']
meats = ['fish', 'pork', 'chicken', 'beef']

for w, m in zip_longest(woods, meats):
    print(f'smoked {w} for {m}')

Our output will then be:

smoked pecan for fish
smoked hickory for pork
smoked cherry for chicken
smoked None for beef

Hope this helps!

If this blog is helpful, please consider helping me pay it backward with a coffee.

Buy Me a Coffee at