The zip() function in Python

The zip() function is particularly useful for those using python to deal with data exploration.

It takes any number of iterators as arguments and returns a zip object, pairing the items in each iterator together.

Code Example

As you can see, the first item of x is paired with the first item of y, then the second of x and the second of y, and so forth.

The return of the zip() function is a zip object, to print its values, we have to convert it to a tuple or list.

>>> x = [23, 54, 33]
>>> y = [83, 71, 22]
>>> z = zip(x, y)
>>> z
<zip object at 0x7f96047b8980>
>>> print(tuple(z))
((23, 83), (54, 71), (33, 22))

zip() is usually used with a for loop:

>>> for z in zip(x, y):
...     print(z)
... 
(23, 83)
(54, 71)
(33, 22)

If the iterators don’t have the same length, the resulting iterator will have the length of the smaller one.

>>> x = [23, 54, 33, 28]
>>> y = [83, 71, 22, 52, 31]
>>> for z in zip(x, y):
...     print(z)
... 
(23, 83)
(54, 71)
(33, 22)
(28, 52)

Since there was no item in x to pair with 31 in y, it wasn’t included in the return of the zip() function.

The zip() function can take as many iterators as you need.

>>> x = [23, 54, 33, 28]
>>> y = [83, 71, 22, 52, 31]
>>> w = [20, 44, 30]
>>> for z in zip(x, y, w):
...     print(z)
... 
(23, 83, 20)
(54, 71, 44)
(33, 22, 30)

And, of course, you can unpack the resulting tuple to format the output more easily:

>>> x = [23, 54, 33, 28]
>>> y = [83, 71, 22, 52, 31]
>>> w = [20, 44, 30]
>>> for first, second, third in zip(x, y, w):
...     print(f'This is the first {first}, this is the second {second}, and this is the third {third}')
... 
This is the first 23, this is the second 83, and this is the third 20
This is the first 54, this is the second 71, and this is the third 44
This is the first 33, this is the second 22, and this is the third 30

To unzip the values back to their originals:

>>> z = ((23, 83), (54, 71), (33, 22))
>>> a, b =  zip(*z)
>>> a
(23, 54, 33)
>>> b
(83, 71, 22)

Finally, as zip() works with iterables, you can also use it with dictionaries:

>>> car_one = {'brand': 'Ferrari', 'model': 'F1', 'color': 'red'}
>>> car_two = {'brand': 'BMW', 'model': 'X1', 'color': 'blue'}
>>> for (key_one, value_one), (key_two, value_two) in zip(car_one.items(), car_two.items()):
...     print(f'{key_one}: {value_one}')
...     print(f'{key_two}: {value_two}')
... 
brand: Ferrari
brand: BMW
model: F1
model: X1
color: red
color: blue