Skip to main content

zip()

The zip() function in Python returns an iterator that aggregates elements from two or more iterables (such as lists, tuples, etc.) into tuples. The tuples contain elements from corresponding positions in the input iterables. The iterator stops when the shortest input iterable is exhausted.

Parameter Values

Parameter Description
iter1, iter2, ...

The iterables to zip together. Can be any iterable such as list, tuple, set, etc.

Return Values

The zip() function returns an iterator of tuples in Python.

How to Use zip() in Python

Example 1:

The zip() function takes iterables (can be multiple iterables) and returns an iterator of tuples where the i-th tuple contains the i-th element from each of the input iterables.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
result = list(zipped)
Example 2:

If the input iterables are of different lengths, zip() will stop as soon as the shortest iterable is exhausted.

list1 = [1, 2, 3]
list2 = ['a', 'b']
zipped = zip(list1, list2)
result = list(zipped)
Example 3:

You can also use the unpacking operator (*) to unzip the zipped elements back into separate lists.

zipped = [(1, 'a'), (2, 'b'), (3, 'c')]
unzipped = list(zip(*zipped))
list1, list2 = unzipped