Extended Zip Functionality with Fillvalue

  • Share this:

Code introduction


This function accepts any number of iterable objects as arguments and returns an iterator where each element is a tuple from these iterables. If some iterables are shorter than others, `fillvalue` is used to fill in the missing values.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Similar to `zip()`, but the shortest input iterable is extended with `fillvalue` for
    the remaining values from longer iterables.
    """
    # Using zip and itertools.zip_longest to achieve the desired functionality
    from itertools import zip_longest

    def _zip_longest(*args, fillvalue=None):
        iterator = iter(args)
        for i in args:
            yield from zip_longest(*[iter(i)] * len(args), fillvalue=fillvalue)

    return _zip_longest(*args, fillvalue=fillvalue)                
              
Tags: