Zip in Python

View source | View history | Atom feed for this file

In mathematics, one can have a function and write , where . Some books take care to remark that since is the domain and , one should in fact write . In Python, this distinction is accomplished using the star (*) in function calls. So for example if one had a sequence of parameters , then one can write

Now, the built-in function zip in Python takes the th element from each iterable in some sequence, and forms a tuple for each , then places all these tuples in one final list. Concretely, suppose we are given some sequence . Incidentally, this sequence can be visualized as an matrix:

Now let us examine what means. The star unpacks the first layer of the sequence, leaving us with Now, will first take the th element from each argument, forming the sequence ; then it will take the elements in position from each argument, forming the sequence ; this process continues until we reach the sequence . Finally, will place everything in a sequence of its own, and we obtain a new matrix: In other words, everything that was horizontal is now vertical, and the converse holds as well—that is, maps each matrix to its transpose (or, more specifically, maps each matrix with row-vectors to the matrix , and then forms row-vectors in the new matrix). If we decide to repeat this operation, we get the original matrix back. In other words, .

To give an example of this identity in Python:

>>> x = (1, 2, 3)
>>> y = (4, 5, 6)
>>> lst = [x, y]
>>> lst == zip(*zip(*lst))
True