Zip in Python
In mathematics, one can have a function f:X×Y→Z and write f(x,y)=z, where x∈X,y∈Y,z∈Z. Some books take care to remark that since X×Y is the domain and (x,y)∈X×Y, one should in fact write f((x,y))=z. In Python, this distinction is accomplished using the star (*
) in function calls. So for example if one had a sequence of parameters (ai)ni=0, then one can write f(⋆(ai)ni=0)=f(a0,…,an)
Now, the built-in function zip
in Python takes the ith element from each iterable in some sequence, and forms a tuple for each i, then places all these tuples in one final list. Concretely, suppose we are given some sequence x=((xi,j)mj=0)ni=0. Incidentally, this sequence can be visualized as an (n+1)×(m+1) matrix:
((x0,0,…,x0,m)⋮(xn,0,…,xn,m))
Now let us examine what zip(⋆x) means. The star unpacks the first layer of the sequence, leaving us with zip((x0,0,…,x0,m),…,(xn,0,…,xn,m)) Now, zip will first take the 0th element from each argument, forming the sequence (x0,0,…,xn,0); then it will take the elements in position 1 from each argument, forming the sequence (x0,1,…,xn,1); this process continues until we reach the sequence (x0,m,…,xn,m). Finally, zip will place everything in a sequence of its own, and we obtain a new matrix: ((x0,0,…,xn,0)⋮(x0,m,…,xn,m)) In other words, everything that was horizontal is now vertical, and the converse holds as well—that is, zip maps each matrix x to its transpose xT (or, more specifically, zip maps each matrix x=(w0,…,wn)T with row-vectors w0,…,wn to the matrix (wT0,…,wTn), 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, x=zip(⋆zip(⋆x)).
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
Tags: computer science, computing, math, programming, Python.
This work is licensed under a Creative Commons Attribution 4.0 International License.