How To Use the Python Zip Function for Multiple Iteration

The Python zip function is an important tool that makes it easy to group data from multiple data structures. It is commonly used to loops over multiple data structures at once, without having to create nested loops.

In this tutorial, I will show you how to use the Python zip function to perform multiple iterations over parallel data structures.

Table of Contents

You can skip to a specific section of this tutorial below:

What is the Python zip Function?

The Python zip function is used to merge multiple objects, called iterables. More specifically, it creates a new object whose elements are tuples. Within a specific tuple, the elements of the iterables are held.

A simple example is helpful to understand the Python zip function. Imagine that you have two Python tuples of names, like this:


a = ("Nick", "Cheryl", "Jim")

b = ("Joseph", "John", "Kyle")

If you wanted to easily pair together the specific entries of the two tuples, the zip function is the perfect solution. Here’s what this loops like:


zip(a,b)

You’ll notice that this returns a special zip object, so the output of this code will look like this:


<zip at 0x10ca43640>

To transform this zip object into a human-readable format, you can use one of Python’s built-in data structure functions.

As an example, here’s how we could transform this zip object into a Python list:


list(zip(a,b))

This returns:


[('Nick', 'Joseph'), ('Cheryl', 'John'), ('Jim', 'Kyle')]

There are many more specifics to the zip function, but that’s its high-level overview.

If you are interested in the technical details, here is the official definition of the Python zip function from the official Python documentation website:

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

More information can be found in the official documentation on the Python zip function here.

For anyone who wants to see the source code of the Python zip function, the language’s maintainers have provided it on the documentation website. Here is the source code for the Python zip function:


def zip(*iterables):

    # zip('ABCD', 'xy') --> Ax By

    sentinel = object()

    iterators = [iter(it) for it in iterables]

    while iterators:

        result = []

        for it in iterators:

            elem = next(it, sentinel)

            if elem is sentinel:

                return

            result.append(elem)

        yield tuple(result)

We will explore more of the characteristics and functionality of the Python zip function throughout the rest of this tutorial.

Click here to return to the Table of Contents

How to Use the Python zip Function With Different Data Structures

In the first example, how the Python zip function can combine two lists into one zip object whose elements are each tuples of length 2.

It is important to understand that the Python zip function is actually capable of working with many different data structures. We will explore how to use Python zip with different data structures in this section.

How to Use Python zip With Tuples

You can pass in two tuples into the Python zip function exactly as we did with lists.

An example is below:


a = ("Nick", "Cheryl", "Jim")

b = ("Joseph", "John", "Kyle")

list(zip(a,b))

The output of this code is below:


[('Nick', 'Joseph'), ('Cheryl', 'John'), ('Jim', 'Kyle')]

As you can see, there is no practical difference between using Python zip with tuples compared to using the function with lists.

How to Use Python zip With Dictionaries

It is possible to use the Python zip function to work with dictionaries, but with some limitations.

Consider the following example:


a = {"mother":"Andrea", "father":"Stephen"}

b = {"youngest":"John", "oldest": "Grace"}

list(zip(a,b))

What do you think the output of this code will be?

The Python zip function zips together the keys of a dictionary by default. Accordingly, here’s the output of the code executed above:


[('mother', 'youngest'), ('father', 'oldest')]

It is possible to zip together the values of the dictionary instead. To do this, call the values method on the dictionary objects when you pass them into the zip function.

Here’s how you would do this using the same data from our earlier example.


a = {"mother":"Andrea", "father":"Stephen"}

b = {"youngest":"John", "oldest": "Grace"}

list(zip(a.values(),b.values()))

Here is the output of this code:


[('Andrea', 'John'), ('Stephen', 'Grace')]

How to Return Different Data Structures From the Python zip Function

Just like we can pass in different data structures as arguments of the Python zip function, it is possible to export different data types as well.

Recall that the default output of the Python zip function is a special zip object that looks like this:


<zip at 0x10ca43640>

To return a list, we wrapped it in the list function. It should be of no surprise, then, that we can use tuple and dict to return tuples and dictionaries.

Here’s an example using the tuple function:


a = ("Nick", "Cheryl", "Jim")

b = ("Joseph", "John", "Kyle")

tuple(zip(a,b))

Here’s the output:


(('Nick', 'Joseph'), ('Cheryl', 'John'), ('Jim', 'Kyle'))

And here’s an example using the dict function:


a = ("Nick", "Cheryl", "Jim")

b = ("Joseph", "John", "Kyle")

dict(zip(a,b))

And here’s the output:


{'Nick': 'Joseph', 'Cheryl': 'John', 'Jim': 'Kyle'}

Click here to return to the Table of Contents

How to Use the Python zip Function With More Than Two Arguments

Although the examples we have seen in this tutorial have only included two iterables, the Python zip function is theoretically capable of accepting unlimited arguments. This section will demonstrate this capability.

To start, let’s define three variables that we’d like to create a zip object with. The variables are below:


canada_cities = ['Toronto', 'Montreal', 'Fredericton']

us_cities = ['New York City', 'San Francisco', 'Houston']

europe_cities = ['London', 'Paris', 'Munich']

We can zip these three objects together by passing them into the Python zip function like this:


list(zip(canada_cities, us_cities, europe_cities))

Here is the output of the function:


[('Toronto', 'New York City', 'London'),

 ('Montreal', 'San Francisco', 'Paris'),

 ('Fredericton', 'Houston', 'Munich')]

As you can see, passing 3 arguments into the Python zip function creates a new data structure whose elements are tuples of length 3.

This extends to larger numbers as well. Said succinctly, passing N arguments into the Python zip function creates a new data structure whose elements are tuples of length N.

Click here to return to the Table of Contents

How the Python zip Function Handles Arguments of Different Length

So far in this tutorial, we have only applied the Python zip functions to data structures of the same length. The zip function can accept arguments with different lengths. I will demonstrate this capability in this section.

Earlier in this tutorial, I embedded the explanation of the Python zip function from the official documentation website.

The description included the following sentence: ‘The iterator stops when the shortest input iterable is exhausted.’

This means that the length of the output of the Python zip function will be equal to the length of its smallest argument.

Let’s consider an example to help solidify this.

Specifically, let’s examine a situation where you have a group of men and a group of women, and you want to pair them together for duo dance lessons. Here’s how the Python zip function could help with this:


men = ['Josiah', 'Micaiah', 'Elijah', 'Joel']

women = ['Chelsea', 'Robyn', 'Olivia']

list(zip(men,women))

Here is the output of this code:


[('Josiah', 'Chelsea'), ('Micaiah', 'Robyn'), ('Elijah', 'Olivia')]

Since the men variable has one extra element than the women variable, then the last element of the men variable (Joel) gets dropped from the Python zip statement.

Click here to return to the Table of Contents

How To Loop Over Multiple Objects in Python Using Python zip

One of the main purposes of the Python zip function is the ability to iterate over multiple objects simultaneously. The syntax for this is very Pythonic and easy to remember, which I why I wanted to conclude this tutorial with this topic.

Looping with Python zip is best understood through an example. Imagine that you have a list of students and lists of grades, like this:


students = ['Nick', 'Joel', 'Taylor']

grades = [95, 75, 85]

If the students are ordered in the same way that the grades are, you could easily print each student’s name and grade with the following loop:


for student, grade in zip(students, grades):

    print(f"{student}'s grade is {grade}")

Here is the output of this code:


Nick's grade is 95

Joel's grade is 75

Taylor's grade is 85

Click here to return to the Table of Contents

Final Thoughts

In this tutorial, you learned how to use the Python zip function to pair elements from different data structures and iterate through them using for loops. If you’re interested in learning more Python concepts, check out my courses Python Fundamentals and Advanced Python for Finance.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:
Written on April 28, 2020