Handling Uneven Length Iterables with Fill Values

  • Share this:

Code introduction


The function takes multiple iterable objects as arguments and returns a list containing the values from these iterables, filling in missing values with fillvalue if their lengths are uneven.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Like zip(), but fills in missing values if the iterables are of uneven length.
    """
    # Using itertools.zip_longest to handle the filling of missing values
    from itertools import zip_longest

    # Using zip_longest to create an iterator that aggregates elements from each of the iterables.
    iterator = zip_longest(*iterables, fillvalue=fillvalue)

    # Using list comprehension to create a list from the iterator
    return list(iterator)                
              
Tags: