Have you seen an actual zip at work? When you close a zip, it takes in 2 teeth (1 from each side) and then locks them up together. The Python zip() function is very similar.
As you can see in the image, the final list consists of a bunch of tupples (enclosed in braces), where each tupple is the nth element from the list.
What is the Python zip() function?
- It has the form zip(iterables). Remember, iterables are objects that allow you to traverse over their values, for example lists and keys() from a dictionary are iterables. [Here’s a quick refresher on iterables in case you’ve forgotten what it is].
- The final output of zip() is an iterator.
- If you pass only 1 input to the Python zip() function, then you simply get back an iterator to that iterable.
- You can unzip a zipped list by adding an ‘*’ (asterix) in front of the iterable passed.
Zip with iterable elements of same length:
Here, we take two lists and then zip them up. This is simple enough since both the lists have exactly the same number of elements.
Zip with iterable elements of different length:
- Whenever the input iterables passed have different lengths, the output iterable has the length of the shortest passed iterable.
- In the following example, ‘table’ is the smallest iterable with only two elements, causing the output to also be of size two.
Unzipping with zip
- You can extract the individual elements from the aggregate iterable using
tupe1, tuple2,.. ,tupple10 = zip(*zipped_iterable or zipped_iterator)
[('Coffee', 40, 'Table 1'), ('Tea', 35, 'Table 2')]
- The below example demonstrates how the aggregate iterable ‘orders’ can be unzipped to give its individual constituent tuples.
If you want to learn more about iterables, then check out this post on the difference between iterables, iterator and yield.