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.
In this tutorial, you will learn the syntax of zip() function, and then its usage with the help of example programs.
Syntax
The syntax of zip() function is
zip(*iterables, strict=False)
where
Parameter | Description |
---|---|
*iterables | One 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
1. 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}')
Output
apple - 25
banana - 10
cherry - 48
2. 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}')
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.