Combining Iterables with Fillvalue

  • Share this:

Code introduction


The function is used to combine multiple iterable objects into an iterator, returning elements from each iterable in a round-robin fashion. If an iterable is exhausted, the specified fillvalue is used to fill in missing values.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables."
    "It returns elements from the iterables on a round-robin basis so that
    the elements from each iterable are consumed as quickly as possible."
    "The iterator stops when the shortest iterable is exhausted, unless
    the 'fillvalue' is specified, in which case missing values in the shorter
    iterables are filled in with 'fillvalue'."

    # Importing from the built-in modules
    from itertools import zip_longest as zip_longest_module

    # Using the zip_longest function from itertools
    return zip_longest_module(*iterables, fillvalue=fillvalue)                
              
Tags: