Creating a Zip Iterator in Python

  • Share this:

Code introduction


Combines elements from each of the iterables into tuples, and returns an iterator. The iterator returns tuples containing one element from each of the iterables. The iterator stops when the shortest iterable is exhausted.


Technology Stack : Combines elements from each of the iterables into tuples, and returns an iterator. The iterator returns tuples containing one element from each of the iterables. The iterator stops when the shortest iterable is exhausted.

Code Type : Built-in functions

Code Difficulty : Intermediate


                
                    
def zip(*iterables):
    "zip(*iterables) --> zip object"
    "zip(object, ...) --> iterator of tuples"
    "Create an iterator that aggregates elements from each of the iterables."
    "The iterator returns tuples containing one element from each of the iterables."
    "The iterator stops when the shortest iterable is exhausted."
    iterator = iter(iterables[0])
    for iterable in iterables[1:]:
        iterator = zip(iterator, iterable)
    return iterator