ZipΒΆ

One more common pattern with lists, besides accumulation, is to step through a pair of lists (or several lists), doing something with all of the first items, then something with all of the second items, and so on. For example, given two lists of numbers, you might like to add them up pairwise, taking [3, 4, 5] and [1, 2, 3] to yield [4, 6, 8].

One way to do that with a for loop is to loop through the possible index values.

You have seen this idea previously for iterating through the items in a single list. In many other programming languages that’s really the only way to iterate through the items in a list. In python, however, we have gotten used to for loop where the iteration variable is bound successively to each item in the list, rather than just to a number that’s used as a position or index into the list.

Can’t we do something similar with pairs of lists? It turns out we can.

The zip function takes multiple lists and turns them into a list of tuples, pairing up all the first items as one tuple, all the second items as a tuple, and so on. Then we can iterate through those tuples, and perform some operation on all the first items, all the second items, and so on.

Here’s what happens when you loop through the tuples.

Or, simplifying and using a list comprehension:

Or, using map and not unpacking the tuple (our online environment has trouble with unpacking the tuple in a lambda expression):

Consider the task from Problem Set 7 where we asked you write a function possible(), as one component of a hangman guesser. It determines whether a word is still possible, given the guesses that have been made and the current state of the blanked word.

We provided a solution that involved iterating through the indexes of the word, checking whether the blanked character was compatible with the word’s character in that same position, given the guesses so far. It’s slightly simplified here, because the original solution was unnecessarily complex.

We can rewrite that using zip, to be a little more comprehensible.

Next Section - Exercises