Python’s zip() function can combine series/iteratable objects as arguments and returns a list of packaged tuples.

zip() takes two or more iterables and pairs up their items. The result is a list of tuples, one tuple per position.

It is the shortest way to walk through two lists at the same time.

If the length of the iterables isn’t equal, then the list returned is that the same length because the shortest sequence.

Syntax

zip([iterable, ...])

Python zip() function

The zip() function can combine two lists like this zip(x,y):

x = [1,2,3,4,5]
y = ['a','b','c','d']
xy = zip(x,y)
print xy
for a,b in zip(x,y):
    print(a)
    print(b)

The program above results in:

[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
1
a
2
b
3
c
4
d

python zip functionDemo 2
So what if you only have one argument in zip() ? The program below shows.

x = [1,2,3,4,5]
xx = zip(x)
print(xx)
for a in zip(x):
    print(a)
for a in zip(x):
    print(a[0])

Outputs:

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

Demo 3
Here’s another demo of the zip function, this time with a dynamic size parameters.

x = [[1,2,3,4],['a','b','c'],[7,8,9]]
y = zip(*x)
print(y)
for a in y:
    print(a)
for a,b,c in zip(*x):
    print(a)
    print(b)
    print(c)

This outputs:

[(1, 'a', 7), (2, 'b', 8), (3, 'c', 9)]
(1, 'a', 7)
(2, 'b', 8)
(3, 'c', 9)
1
a
7
2
b
8
3
c
9

Another zip() demo
Just for understanding, here is another demo of the zip function.

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # Packaged list of tuple
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # The number of elements matches the shortest list
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # In contrast to zip, which can be understood as decompression, the inverse process of zip can be used to transpose the matrix
[(1, 2, 3), (4, 5, 6)]

Things worth knowing

  • It stops at the shortest iterable. Two lists of different length give you the length of the shortest.
  • zip() with no arguments gives you nothing, so with one list you get tuples of one item.
  • strict=True (Python 3.10 and up) raises an error instead of dropping the extra items.
  • You can turn the result back into two lists with zip(*zipped).
  • It works with any iterable, so strings, tuples and even a range work fine.

Since zip returns an iterator, you can loop over it directly without converting it to a list first.

If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.