Extended Zip Function for Iterables of Varying Lengths

  • Share this:

Code introduction


This function is an extended version of the zip function, which merges multiple iterable objects into a list of tuples. If an iterable object does not have enough elements, it is filled with fillvalue. This function is especially suitable for dealing with lists of different lengths.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Zip equivalent that allows different number of items in input iterables.
    """
    from itertools import zip_longest

    def _is_not_none(value):
        return value is not None

    for result in zip_longest(*args, fillvalue=fillvalue):
        if not all(_is_not_none(item) for item in result):
            return result

    return args                
              
Tags: