Zip

Last updated: Mon. Sep. 14, 2026

The zip() function loops over several iterables in parallel and produces tuples with an item from each one. It has the syntax zip(*iterables, strict=False). It returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the iterables passed to it.

The zip() function is lazy: This means that the items won’t be processed until the iterable is looped over. This can either be done by a for loop or by wrapping it in a list.

Let's demonstrate this with a list of numbers and another of fruits:

nums = [1, 2, 3]

fruits = ['apples', 'bananas', 'grapes']

The output would be [(1, 'apples'), (2, 'bananas'), (3, 'grapes')]

The iterables passed to zip() can have different lengths and Python provides three methods of handling this issue: One way is that the default design of zip() makes it stop when the shortest iterable is finished. This means that tt will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable. We can examine this in this example:

nums = [1, 2, 3]

names = ['Alice', 'John', 'Peters', 'Joy']

print(list(zip(nums, names)))

Will return [(1, 'Alice'), (2, 'John'), (3, 'Peters')]. Notice that the extra name 'Joy' was ignored.

Another way to handle this is to use the strict=True argument of the zip() function. Its output is the same as using the regular zip() but will raise a ValueError if one iterable is exhausted before the others::

For example print(list(zip(nums, names, strict=True))) will raise ValueError: zip() argument 2 is longer than argument 1. Always use the strict=True option when you want your iterables to be of the samelength.

The third way to do this is to use the itertools.zip_longest() to fill up shorter iterables with a constant value. This will make all the iterables have the equal length.

import itertools

nums = [1, 2, 3, 4]

fruits = ['apples', 'bananas', 'grapes']

If you run print(list(itertools.zip_longest(nums, fruits, fillvalue='empty'))), you will get [(1, 'apples'), (2, 'bananas'), (3, 'grapes'), (4, 'empty')].

« Home