zip(*iterables)

Creates an tuple of all iterables items and return an iterator of the tuple.


In [65]:
list(zip())


Out[65]:
[]

In [66]:
x = [1,2,3]
it = zip(x)
list(it)


Out[66]:
[(1,), (2,), (3,)]

In [111]:
x = [1, 2, 3, 4, 5, 6]
y = ["a", "b", "c"]
it = zip(x,y) # Tuple length is always min of all input iterables. 
ls = list(it)
print(ls)


[(1, 'a'), (2, 'b'), (3, 'c')]

unzip

To unzip a list of tuples add *. If tuples have different lengths, the smallest is used for unzipping.


In [122]:
x, y = zip(*ls)
print(x)
print(y)


(1, 2, 3)
('a', 'b', 'c')

In [124]:
x = [(1,2, 4), (3,4)]
x, y = list(zip(*x))
print(x)
print(y)


(1, 3)
(2, 4)