Zip

There are a few techniques that you may employ occasionally while manipulating your collections. Zip is one of them.

Zip is used to transform multiple collections into a single collection of tuples of respective elements.

list1 = ['a', 'b', 'c']
list2 = [1, 2, 3, 4]
zipped = zip(list1,list2)
print(type(zipped))

for i in zipped:
    print(i)

output:

< class 'zip' >
0 ('a', 1)
1 ('b', 2)
2 ('c', 3)

In the above example you convert two lists of different data types into a zip object containing tuples with elements from each list in the order in which the zip was invoked. If the length of the two lists are different then the zip stops at the length of the shortest list.

A zip object can be enumerated as shown above or you can convert it into a list by using the list function. However once enumerated or converted to a list, the zip object will be empty and cannot be reused. See the example below;

list1 = ['a', 'b', 'c']
list2 = [1, 2, 3, 4]
zipped = zip(list1,list2)
tuple_list = list(zipped);

for i in tuple_list:
    print(i)   # this will print the tuples.

for i,j in enumerate(zipped):
    print(i,j)  # this will not be invoked as the zipped is empty

zip can be used on any collection; set, tuple, list etc.. One point to note in set is, since set does not maintain the order, you will not be sure which elements form the resultant tuple.

results matching ""

    No results matching ""