Reading Time: 1 minutes
Using zip() in Python
The constructor of builtin class zip takes iterables as inputs and returns an iterator of tuples of corresponding elements. The population of the iterator stops when the shortest input iterable is exhausted. Since it returns an iterator, the __next__() method is used fetch the next tuple. to Let's look at a few examples:
# TWO ITERABLES AS INPUTS >>> zipOne = zip( [1, 2, 3, 4], [5, 6, 7, 8, 9] ) >>> zipOne.__next__() (1, 5) >>> zipOne.__next__() (2, 6) >>> zipOne.__next__() (3, 7) >>> zipOne.__next__() (4, 8) >>> zipOne.__next__() Traceback (most recent call last): zipOne.__next__() StopIteration >>> zipOne = zip( [1, 2, 3, 4], [5, 6, 7, 8, 9] ) >>> for element in zipOne: print(element) (1, 5) (2, 6) (3, 7) (4, 8) >>> zipOne = zip( range(5), range(5, 10) ) >>> for element in zipOne: print(element) (0, 5) (1, 6) (2, 7) (3, 8) (4, 9) >>> zipOne = zip( range(5), range(5, 10) ) >>> zipOne.__next__() (0, 5) >>> zipOne.__next__() (1, 6) >>> zipOne.__next__() (2, 7) >>> zipOne.__next__() (3, 8) >>> zipOne.__next__() (4, 9) >>> zipOne.__next__() Traceback (most recent call last): zipOne.__next__() StopIteration # FOUR ITERABLES AS INPUT >>> zipTwo = zip('Have', 'you', 'met', 'Ted') >>> for element in zipTwo: print(element) ('H', 'y', 'm', 'T') ('a', 'o', 'e', 'e') ('v', 'u', 't', 'd')