Python Beginner Concepts Tutorial

Zip Function

Sometimes, you may be passed two data separate data structures that have related information.

A simple example could be a list of grades on an exam in alphabetical order of students' names and another list of the student's names.

In [12]:
grades = [100, 92, 95]
In [13]:
names = ["Jill", "Emily", "Taylor"]

Because these two are related, we ought to put them in a single data structure.

One way to easily do this is use the built-in Python function called zip. This function takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence.

In [14]:
zip(names, grades)
<zip at 0x1105f2dc8>

This result is a zip object. We'll explain this concept later.

If we want to see our result in a list, we can use Python's built-in list function and pass in this zip object.

In [15]:
list(zip(names, grades))
[('Jill', 100), ('Emily', 92), ('Taylor', 95)]

We're returned a list of tuples in which each tuple contains the name of the student and their grade on the exam.

Alternatively, we can loop over the elements in our zip object.

In [16]:
for name_grade in zip(names, grades):
('Jill', 100)
('Emily', 92)
('Taylor', 95)

Each tuple contains the name of the student and their grade on the exam.

We can also use tuple assignment in a for loop to extract the elements in each tuple.

In [17]:
for name, grade in zip(names, grades):
    print("{0} received a {1} on the exam".format(name, grade))
Jill received a 100 on the exam
Emily received a 92 on the exam
Taylor received a 95 on the exam

Notice how we assigned the variable name to the first item in each tuple and grade to the second item.

Then, we printed a string that uses these two variables to explain their relevance.

The zip object (that we returned above) is an iterator, which is any object that iterates through a sequence.

Iterators are similar to lists in some ways; but unlike lists, you can't use an index to select an element from an iterator.