zip() Builtin Function

Python zip()

Python zip() builtin function is used to iterator over multiple iterable parallelly. The resulting iterator produces tuples, where each tuple contains respective items from input iterables.

Syntax

The syntax of zip() function is

zip(*iterables, strict=False)

where

*iterablesone or more comma separated iterables
strict[Optional] strict=False ignores if the iterables are of different lengths. If strict=True, then the iterables must be of same length.

Examples

Zip Two Lists

In the following program, we take two lists: names and quantities; and iterate over both of them parallelly using zip().

Python Program

names = ['apple', 'banana', 'cherry']
quantities = [25, 10, 48]

for (name, quantity) in zip(names, quantities) :
    print(f'{name} - {quantity}')
Run

Output

apple - 25
banana - 10
cherry - 48

Zip Two Lists of Different Lengths

In the following program, we take two lists: names and quantities; and iterate over both of them parallelly using zip(). But in this case, we take names list of length 4, and quantities list of length 2. Since 2 is the highest common length between the two input iterables, zip() function returns an iterator that produces only two items.

Python Program

names = ['apple', 'banana', 'cherry', 'mango']
quantities = [25, 10]

for (name, quantity) in zip(names, quantities) :
    print(f'{name} - {quantity}')
Run

Output

apple - 25
banana - 10

Summary

In this tutorial of Python Examples, we learned the syntax of zip() builtin function, and how to iterate over multiple iterables parallelly, with the help of examples.