What is the zip() function in Python?

The zip() function takes iterables and aggregates their elements based on their order in the iterable.

Note: An Iterable is an object which can be repeated over and over. It generates an iterator when passed to iter() method.

The zip() function returns an iterator of tuples, where the ith tuple contains the ith element from each of the iterables.

svg viewer

Syntax

Here is the function signature for the zip() function in Python:

# function signature for the zip() method
zipped_iterator = zip(iterator1, iterator2,...)

As shown above, the zip function takes any number of iterables and returns an iterator of tuples.

Input

  • iterables: Any iterables such as lists, strings, etc.

Output

  • Returns: An iterator of tuples based on the input iterables.

Examples

Let’s take a look at how the zip() function works.

names = ['John', 'Danny', 'Tyrion', 'Sam']
marks = [20, 10, 5, 40]
zipped_iterator = zip(names, marks)
# Converting iterator to list
zipped_values = list(zipped_iterator)
print(zipped_values)

The zip() function returns an iterator. It is important to convert that iterator into an iterable such as a list, dict, set, etc.


Iterables of different lengths

If the passed iterables are of different lengths, then the returned iterator takes the length of the shortest iterator passed to the function. For example:

names = ['John', 'Danny']
marks = [20, 10, 5, 40]
zipped_iterator = zip(names, marks)
# Converting iterator to list
zipped_values = list(zipped_iterator)
print(zipped_values)

In the above example, the names list has a smaller length than the marks list. As a result, the returned iterator is the same length as the names list.


Multiple Iterables

The zip() function also works for more than two iterables, for example:

names = ['John', 'Danny', 'Tyrion', 'Sam']
powers = ['Sales', 'Marketing', 'IT', 'Human Resource']
marks = [20, 10, 5, 40]
zipped_iterator = zip(names, powers, marks)
# Converting iterator to list
zipped_values = list(zipped_iterator)
print(zipped_values)

In the above code the ith element of each iterable is combined to form the ith tuple.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved