The Python zip() Function

The Python zip() function is used to combine two or more iterables into one iterable of tuples. This works by taking the first value of each iterable, combining them into a tuple and then adding that to the new zip object. The process is repeated for each value until complete.

 

In this tutorial, we will learn how to create a collection of tuples from any number of iterables in Python.

 

Using the zip()

Let's create a couple of lists and then zip them together using zip() and look at what the output is. To use the zip() function, pass the iterables as arguments inside the () (parenthesis) of the function.

 

numbers_1 = [1, 3, 5, 7, 9, 11]
numbers_2 = [2, 4, 6, 8, 10]

result = zip(numbers_1, numbers_2)

print(result)
for t in result:
    print(t)
<zip object at 0x10569cb00>
(1, 2)
(3, 4)
(5, 6)
(7, 8)
(9, 10)

 

As you can see from the output above a zip object was created containing tuples, each side of which has values from each list.

 

note - An important behaviour of zip() to be aware of is that it will use the shortest iterable to determine when to stop adding tuples.

 

numbers_1 = [1, 3, 5, 7, 9, 11]
numbers_2 = [2, 4]

result = zip(numbers_1, numbers_2)

for t in result:
    print(t)
(1, 2)
(3, 4)

 

Only two tuples were created due to numbers_2 only having two values.

 

More than two Lists

Let's see how zip() behaves when more than two iterables are combined.

 

numbers_1 = [1, 3, 5, 7, 9, 11]
numbers_2 = [2, 4, 6, 8, 10]
numbers_3 = [12, 13, 14, 15, 16]

result = zip(numbers_1, numbers_2, numbers_3)

for t in result:
    print(t)
(1, 2, 12)
(3, 4, 13)
(5, 6, 14)
(7, 8, 15)
(9, 10, 16)

 

It is even clearer in the above example to see how zip() is building tuples.

 

Unzip Values with zip()

it is possible to unzip zipped values by passing variables to represent the lists and putting a * (asterisk) inside before the first argument inside zip().

 

numbers_1 = [1, 3, 5, 7, 9, 11]
numbers_2 = [2, 4, 6, 8, 10]

result = zip(numbers_1, numbers_2)

n_1, n_2 = zip(*result)

print(list(n_1))
print(list(n_2))
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]

 

Conclusion

You now know what the zip() function in Python does, how it behaves and how to use it. The main thing to watch out for is the last elements from lists longer than the shortest will be excluded.

iterable zip combine merge tuple