Python#s zip_longest Function Explained

  • Share this:

Code introduction


This function takes an arbitrary number of iterable objects as input and returns an iterator that yields a tuple containing the next element from each input iterable. If an iterable is exhausted, fillvalue is used to fill the gap.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    from itertools import zip_longest as zip_longest_itertools
    from collections import deque

    def fill(iterable, fillvalue):
        iterator = iter(fillvalue)
        for element in iterable:
            yield element
            next(iterator)

    longest = max((deque(iterable), len(iterable)) for iterable in iterables if iterable)
    longest_length = len(longest[0])
    for i in range(longest_length):
        for iterable in iterables:
            if i >= len(iterable):
                yield fillvalue
            else:
                yield iterable[i]