Python Zip Longest Function: Combining Iterables with Fillvalue

  • Share this:

Code introduction


Combines multiple iterables (sequences) by taking elements from each in turn. The iterator stops when the shortest input iterable is exhausted, after which the remaining elements of longer iterables are filled with the fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Zip together multiple iterables (sequences) by taking the elements from each in turn.
    The iterator stops when the shortest input iterable is exhausted, after which the remaining
    elements of longer iterables are filled with the fillvalue.
    """
    from itertools import zip_longest

    return list(zip_longest(*args, fillvalue=fillvalue))                
              
Tags: