zip is a built-in function that takes two or more sequences and “zips” them into a list of tuples where each tuple contains one element from each sequence. In Python 3, zip returns an iterator of tuples, but for most purposes, an iterator behaves like a list.
This example zips a string and a list:
>>> s = 'abc'>>> t = [0, 1, 2]>>> zip(s, t)[('a', 0), ('b', 1), ('c', 2)]
The result is a list of tuples where each tuple contains a character from the string and the corresponding element from the list.
If the sequences are not the same length, the result has the length of the shorter one.
>>> zip('Anne', 'Elk')[('A', 'E'), ('n', 'l'), ('n', 'k')]
You can use tuple assignment in a for loop to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]for letter, number in t:print number, letter
Each time through the loop, Python selects the next tuple in the list and assigns the elements to letter and number. The output of this loop is:
0 a1 b2 c
If you combine zip, for and tuple assignment, you get a useful idiom for traversing two (or more) sequences at the same time. For example, has_match takes two sequences, t1 and t2, and returns True if there is an index i such that t1[i] == t2[i]:
def has_match(t1, t2):for x, y in zip(t1, t2):if x == y:return Truereturn False
If you need to traverse the elements of a sequence and their indices, you can use the built-in function enumerate:
for index, element in enumerate('abc'):print index, element
The output of this loop is:
0 a1 b2 c