Q2.4.6zip and its inverse
Explain why zip(*z) is the inverse of z = zip(a, b) – that is, whilst z pairs the items: (a0, b0), (a1, b1), (a2, b2), ..., zip(*z) separates them again: (a0, a1, a2, ...), (b0, b1, b2, ...)
Show solution
Recall that the * operator unpacks a tuple into a positional argument list to a function. So if z = zip(a,b) is the (iterator) sequence: (a0,b0), (a1, b1), (a2, b2), .... Unpacking this sequence in the call zip(*z) is equivalent to calling zip with these tuples as arguments:
zip((a0, b0), (a1, b1), (a2, b2), ...)}
zip takes the first and second items from each tuple in turn, reproducing the original sequences:
(a0, a1, a2, ...), (b0, b1, b2, ...)