Aggregating Iterables with Zip Longest

  • Share this:

Code introduction


The function uses the `zip_longest` function from the `itertools` library to merge multiple iterable objects into an iterator, so that iterable objects of different lengths can be output in pairs, and the missing parts are filled with `fillvalue`.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables.
    The iterator returns pairs, where the first element comes from the first
    of the iterables and the second element comes from the second, and so on.
    The returned pairs have equal length. If the iterables are of uneven length,
    missing values are filled-in with fillvalue. Default is None.
    """
    from itertools import zip_longest as itzip_longest

    def pair_generator():
        for pair in itzip_longest(*iterables, fillvalue=fillvalue):
            yield pair

    return pair_generator()

# JSON representation                
              
Tags: