Zip: Make Aggregation Easier

zip

It is easy to aggregates elements from iterables using zip:

1
2
3
4
5
6
7
8
9
10
11
'''
zip(*iterables)
'''
number = [1, 2, 3]
letters = ['a', 'b', 'c']
print(list(zip(number, letters)))
print(list(zip(range(5), range(100)))) # the number of zip is equal to the shortest iterable
'''
[(1, 'a'), (2, 'b'), (3, 'c')]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
'''

We can even use zip to generate a dictionary:

1
2
3
4
5
6
fields = ['name', 'job']
items = ['John', 'worker']
print(dict(zip(fields, items)))
'''
{'name': 'John', 'job': 'worker'}
'''

If the iterables are ordered (e.g. list, dict), zip will output the tuples in order, otherwise the order is indeterminate.

1
2
3
4
5
6
number = {1, 2, 3}
letters = {'a', 'b', 'c'}
print(list(zip(number, letters)))
'''
[(1, 'b'), (2, 'c'), (3, 'a')]
'''

unzip

zip can also work as unzip, which returns tuples:

1
2
3
4
5
6
7
8
9
10
11
'''
zip(*pairs)
'''
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
number, letters = zip(*pairs)
print(number)
print(letters)
'''
(1, 2, 3)
('a', 'b', 'c')
'''