Lesson 9
No Object is an Island
Chapter 4: More iterable objects
zip
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])
.