5️⃣

14.5 Zip

Zip

Zip takes two separate inputs, usually lists, and creates a tuple using corresponding elements of each input. You want to use zip when you need to group corresponding elements together for whatever reason. Here is an example:
a = [1, 2, 3] b = ['a', 'b', 'c'] c = ['!', '@', '#'] G = zip(a, b, c) print(list(G)) # prints [(1, 'a', '!'), (2, 'b', '@'), (3, 'c', '#')]
Corresponding elements mean elements with the same index relative to their lists. In the example above, 1 corresponds to ‘a’ and ‘!’, as they share the index of 0. 2 corresponds to ‘b’ and ‘@’. 3 corresponds to ‘c’ and ‘#’.
 
What happens if one of the lists (or other inputs) has a greater length than the others? Well, elements with no other corresponding elements get ignored. Here’s an example:
list_one = [1, 2] list_two = [41] for pair in zip(list_one, list_two): print(pair) # this would only print (1, 41)
In this example, 2 gets ignored because there is no corresponding pair
 
As you can see, you can use zip with any number of inputs and lists. However, they’re really useful to create dictionaries since, using two lists (or other inputs), you can have the first list’s elements be the key and the second list's elements are the values, forming key-value pairs. Here’s an example:
countries = [' Japan', 'America', 'South Korea', ' China'] numbers = [1, 2, 3, 4] dict1 = dict(zip(countries, numbers)) print(dict1) # prints {' China': 4, ' Japan': 1, 'America': 2, 'South Korea': 3}
In the above example, the keys of dict1 are the elements in countries while the values of dict1 are the corresponding elements in numbers.
There are other ways of grouping corresponding elements, but zip is one of the most elegant and short ways to do it.
View code on GitHub.

Practice

Darwin's Raccoon

Darwin is observing raccoons’ growths on an unnamed island. He spends 7 days in total on this island, and every day, he would record the average growth of raccoons in inches. He loses data on day 7, so he decides to make the data on that day to be the maximum of the previous 6 days. He needs to make a dictionary for use later where the key is the day number and the value is the average growth of raccoons on that day. You help him make the dictionary. Use zip to solve this problem.

Pokemon Presentation

You’re a teacher giving a presentation on the types of pokemon. You have a list pokemons_list, and you have another list types_list(this has the types of the pokemon in pokemons_lists in the same order). Since you are presenting, print “[insert pokemon] is a [insert type] type” for all the pokemon in pokemons_list with their corresponding types in types_list. Use zip to solve this problem.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.