This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: More iterable objects

zip

face Josiah Wang

Python also provides a zip object to help you group elements in two lists together.

It is probably easier explained with an example. So study the example below to understand how it works!

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> print(list(zipped))
[(1, 4), (2, 5), (3, 6)]
>>> for (a, b) in zip(x, y):
...    print(f"{a}, {b}")
...
1, 4
2, 5
3, 6

It’s called zip because it acts like a zipper that zips up the left and right ‘teeth’ alternately! Of course, you can zip up more than two lists: e.g. zip([1,2,3],[4,5,6],[7,8,9]).