Creating an Aggregated Iterator for Uneven Length Iterables

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from multiple iterable objects and returns tuples. If the iterables are of uneven length, missing values are filled in with fillvalue.


Technology Stack : itertools

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables.
    The iterator returns pairs of elements from the iterables. If the iterables
    are of uneven length, missing values are filled-in with fillvalue.
    Returns a zip object, which is an iterator, so you should use it in a for-loop.
    """
    from itertools import zip_longest as _zip_longest
    return _zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: