Creating a Zip Longest Iterator in Python

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from multiple iterable objects. If the iterables are of unequal length, a fillvalue is used to fill in missing values.


Technology Stack : itertools

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables.
    The iterables must be of the same length or the shortest iterable is repeated
    until the longest is exhausted. The iterator stops when the longest iterable is exhausted.
    An optional fillvalue is used for missing values when the iterables are of unequal length.
    "
    from itertools import zip_longest as zip_longest_itertools

    return zip_longest_itertools(*iterables, fillvalue=fillvalue)                
              
Tags: