Lesson 12: Python zip() function

zip() takes two or more lists and combines them for you.

Similar to map and filter, you need to use it inside list function if you want to display meaningful values. Otherwise it will just print the memory address of the function object.

zip() will return tuples in a list, something that looks like:
After that it’s very east to address the items. First item comes from the first list that’s being merged and second item in the tuple comes from the second list.

Let’s see some examples:

Function 1: zip()

zip() function in Python will take two or more lists as argument and it will return tuples consisted of pairs or group of threes, fours… depending how many lists were passed as argument.

Used Where?

When processing lists, if you need to merge them quickly zip() offers a great solution for that.

Syntax do(s)

1) just use zip() function with multiple lists inside parenthesis separated with comma.

Syntax don't(s)

1) don't forget to convert zip object to a list or tuple if you are going to read and interpret the results.

Example 1: zip()

Let’s say we got 2 lists with related values:
First city names, Second their PM2.5 air pollution values of 5 most populated cities in the world.
lst1 = ["Kanpur", "Faridabad", "Bhutan", "Gaya", "Varanasi"]
>>> lst2 = [173, 171, 150, 149, 146]
>>> lst_merged = zip(lst1, lst2)
>>> print(list(lst_merged))

[(‘Kanpur’, 173), (‘Faridabad’, 171), (‘Bhutan’, 150), (‘Gaya’, 149), (‘Varanasi’, 146)]

Sadly, the list demonstrates South Asia’s ongoing struggle with pollution. PM2.5 is abbreviation for Particulate Matter that is 2.5 micrometers or smaller in diameter and shows air pollution. 2.5 micrometers or very small particles are  dangerous and can be inhaled by humans or animals. We have to do something fast to fix these problems on our planet 🌏

Example 2: Working with nested lists in zip function

You can also use star notation with * (asterix) operator in Python with zip function. Check out this transformation:
lst = [[1,2,3], [4,5,6]]

a = list(zip(*lst))

[(1, 4), (2, 5), (3, 6)]

What happens here is * notation is used to unpack the outer list exposing inner lists and then zip function is used to combine them with each other resulting in tuples of pairs in a list.

This is the Python syntax everybody falls in love with. It has a zen to it and its addictive. Okay, let’s see some other examples.

Example 3: zip() with 3 lists

Adding the country data as a 3 list might make sense.

lst1 = ["Kanpur", "Faridabad", "Bhutan", "Gaya", "Varanasi"]
lst2 = [173, 171, 150, 149, 146]
lst3 = ["India", "India", "Bhutan", "India", "India"]

lst_merged = zip(lst1, lst2, lst3)


[(‘Kanpur’, 173, ‘India’), (‘Faridabad’, 171, ‘India’), (‘Bhutan’, 150, ‘Bhutan’), (‘Gaya’, 149, ‘India’), (‘Varanasi’, 146, ‘India’)]

Now each tuple consists of 3 elements coming from each list. And everything is in a list so it’s a list of tuples.

Printing the zip function object

Python zip function returns a zip object which can be used for iterations directly which will be very memory efficient. At the same time we can also build Python sequences such as Python lists from this zip object.

Example 4: Printing the zip function

We can iterate through zip objects that we get when we use the zip function. However when we print it directly we will get something like this:

lst = [1,2,3]
a = zip(lst, lst2)


<zip object at 0x000002AC764736C8>

This is a zip object’s memory address which is a very efficient representation of data but it’s not very readable to human eyes. That’s why converting the result to a list might make sense in some situations and make it more presentable.

But if you are just using it in an iteration in a for loop, while loop, lambda, map, filter, list comprehension, dict comprehension etc. then just let it be as it will be more efficient in the operation.

Tips (optional)

  1. 1- Zip objects are useful as they are. Sometimes when you have multiple separate collections that are related to each other it just makes sense to consolidate them under one roof and that’s exactly what zip function does.
  2. Additionally, zip objects can often be used inside other functions and iterations.
    • In the following example we will use zip function to create a zip object which merges two lists and it will be used in a for loop’s body as the iterable.
    • Also, we will utilize a couple of string methods, namely lower() and replace() to create the exact string format we need for our dictionary keys.

Let’s see the examples.

Example 5: Creating a dictionary using zip function

Here are some of the most famous women athletes in skiing and their international alpine ski competition medal counts. Unfortunately we have the values in separate Python list but thankfully they are in exact right order.

names = ["Sofia Goggia", "Mikaela Shiffrin", "Wendy Holdener", "Lindsey Vonn", "Frida Hansdotter", "Michelle Gisin", "Ragnhild Mowinckel", "Federica Brignone", "Tina Weirather", "Ester Ledecka"]
medals =[3, 10, 7, 11, 6, 2, 3, 2, 2, 6]

zipped_lst = zip(names,medals)

dict = {}

for i in (zipped_lst):
    dict[i[0]] = i[1]

{‘Sofia Goggia’: 3, ‘Mikaela Shiffrin’: 10, ‘Wendy Holdener’: 7, ‘Lindsey Vonn’: 11, ‘Frida Hansdotter’: 6, ‘Michelle Gisin’: 2, ‘Ragnhild Mowinckel’: 3, ‘Federica Brignone’: 2, ‘Tina Weirather’: 2, ‘Ester Ledecka’: 6}

By this little change using lower and replace string methods in Python we can get our desired results.

    dict[i[0].lower().replace(" ", "")] = i[1]

{‘sofiagoggia’: 3, ‘mikaelashiffrin’: 10, ‘wendyholdener’: 7, ‘lindseyvonn’: 11, ‘fridahansdotter’: 6, ‘michellegisin’: 2, ‘ragnhildmowinckel’: 3, ‘federicabrignone’: 2, ‘tinaweirather’: 2, ‘esterledecka’: 6}


Advanced Concepts (Optional)

1- zip function works really well with list comprehension and dict comprehension.

Example 6: Dict comprehension with zip function

If we jump ahead to the dict comprehensions with Python which will make dictionary building much more compact and practical than it would conventionally be in some cases. Previous example is a great opportunity to demonstrate this compact approach and incorporate zip function as well.

If you’re not familiar with dict comprehension please check out this lesson. Or consider revisiting this example after completing dict comprehension in Python.

Here is the same example handled in a much more compact way.

names = ["Sofia Goggia", "Mikaela Shiffrin", "Wendy Holdener", "Lindsey Vonn", "Frida Hansdotter", "Michelle Gisin", "Ragnhild Mowinckel", "Federica Brignone", "Tina Weirather", "Ester Ledecka"]
medals =[3, 10, 7, 11, 6, 2, 3, 2, 2, 6]

zipped_lst = zip(names,medals)

dict = {i[0].lower().replace(" ", "") : i[1] for i in zipped_lst}


{‘sofiagoggia’: 3, ‘mikaelashiffrin’: 10, ‘wendyholdener’: 7, ‘lindseyvonn’: 11, ‘fridahansdotter’: 6, ‘michellegisin’: 2, ‘ragnhildmowinckel’: 3, ‘federicabrignone’: 2, ‘tinaweirather’: 2, ‘esterledecka’: 6}

Pythonic indeed!

Next Lesson: map() function

Autumnal Forest Renewal - nicholas bott

Nicholas Bott

Autumnal Forest Renewal

Autumnal Forest Renewal by Nicholas Bott