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.
Here is the function signature for the zip()
function in Python:
# function signature for the zip() methodzipped_iterator = zip(iterator1, iterator2,...)
As shown above, the zip function takes any number of iterables and returns an iterator of tuples.
iterables
: Any iterables such as lists, strings, etc.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 listzipped_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.
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 listzipped_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.
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 listzipped_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