Zip function in Python

Ann
2 min readNov 3, 2020

Last time, I showed you how to iterate through one list. But sometimes, you will have to iterate through more than one list. For example, you have two lists. One has even numbers, and the other one has odd numbers. You want to find the sum of the first two numbers, the second two numbers, etc. In python, there is a built-in operator that can zip two lists together, the zip() function.

Here is the code(Input):

my_list = [1,3,5,7,9]
my_other_list = [2,4,6,8,10]
for item1, item2 in zip(my_list, my_other_list):
print(item1 + item2)

Output:

3
7
11
15
19

I ask myself, can you iterate through more than two lists? Let me experiment:

Input:

my_1st_list = [1, 3, 5, 7, 9]
my_2nd_list = [1.5, 2.5, 3.5, 4.5, 5.5]
my_3rd_list = [2, 4, 6, 8, 10]
for item1, item2, item3 in zip(my_1st_list, my_2nd_list, my_3rd_list):
print(item1 + item2 + item3)

Output:

4.5
9.5
14.5
19.5
24.5

Oh! So, you can iterate through more than two lists!

Still, I’m still kind of curious. What if the lists are different sizes? by that, I mean what if one list is longer than the other? Let me see:

Input:

my_longest_list = [1, 3, 5, 7, 9, 11]
my_long_list = [1.5, 2.5, 3.5, 4.5, 5.5]
my_shortest_list = [2, 4, 6, 8, 10]
for item1, item2, item3 in zip(my_longest_list, my_long_list, my_shortest_list):
print(item1 + item2 + item3)

Output:

4.5
9.5
14.5
19.5
24.5

Oh! Okay. So, the output was the same as last time where I tried if we can iterate through more than 2 lists. I had one list where the numbers were the same. I only added to the other 2. Python truncated or trimmed the longer lists the length of the shortest one.

In conclusion, you can iterate through more than two lists using a built-in operator that can zip two or more lists together. If you ask python to zip lists that are not the same size together, then python will make them all the same size by truncating the longer list(s) to the length of the shortest one.

--

--