Zipping and unzipping
Let's imagine we have two lists of matching lengths, and we wish to pair their elements together to perform a specific task. This is a common scenario in programming, let's see how we may do this using a for loop with an index counter to achieve this, as shown in the code editor below.
In the example above, we have two lists: one with student names, and another with the number of cats each student has. We use a for loop to print out each student's name along with their respective number of cats. This approach works, but it is fragile considering we need to ensure the two lists are in sync.
Enter zip
, a built-in function in Python that makes
our task simpler and our code cleaner. The zip
function
takes two or more sequences (like lists or tuples) and 'zips' them
together into a single iterable of tuples, where each tuple contains
one element from each of the input sequences.
In this revised example, we use zip
to combine the two
lists into pairs of student names and cat counts, making the for
loop simpler and easier to read. We then should be ready to unpack this
pair into two iterators - student
and n_cats
.
Sometimes we may receive two lists we would like to iterate over,
coming in nested together within another list. We can in essence
"unzip" this nested list into two separate lists using the
zip
function. To make this unzip action work,
we need to add a multiply operator *
before the list
name, which tells the interpreter to unpack the list into its elements.
Now, what happens if our lists are of different lengths?
In this case, zip
will stop creating tuples when
the shortest input iterable is exhausted, and any remaining
elements in the longer iterables will be ignored (poor Katherine).
Finally, can we zip together more than two lists? Absolutely! We can zip together as many lists as we need, following the same logic and syntax.