Combining Iterables with zip_longest

  • Share this:

Code introduction


The `zip_longest` function is used to combine multiple iterable objects into a single iterator. If the length of the iterable objects is not equal, `fillvalue` is used to fill in the missing values.


Technology Stack : The `zip_longest` function is used to combine multiple iterable objects into a single iterator. If the length of the iterable objects is not equal, `fillvalue` is used to fill in the missing values.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "zip_longest(*iterables, fillvalue=None) -> zip_longest object
    
    Zip the iterables together into a single iterable.
    
    The iterator returns pairs of the form (i1, i2, ...), where i1 is the next
    value from the first iterable, i2 from the second, and so on.
    
    If the iterables are of uneven length, missing values are filled-in with
    fillvalue. Default is None.
    
    Args:
        *iterables: An arbitrary number of iterables.
        fillvalue: Value to use for missing values if the iterables are of uneven length.
    
    Returns:
        An iterator that aggregates elements from each of the iterables.
    "
    from itertools import zip_longest as _zip_longest
    return _zip_longest(*iterables, fillvalue=fillvalue)