Python zip_longest Function Overview

  • Share this:

Code introduction


This function is used to iterate over multiple iterable objects and returns an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled in with fillvalue.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    # This function will iterate over several iterables (args) and return an iterator that aggregates elements from each of the iterables.
    # If the iterables are of uneven length, missing values are filled-in with fillvalue.
    # Using deque to handle the filling of values when the shortest iterable is exhausted.

    def fill_values(iterable):
        # Generator that yields elements from the iterable and fills with None if the iterable is exhausted.
        for element in iterable:
            yield element
        while True:
            yield fillvalue

    zipped = zip_longest(*map(fill_values, args))
    return zipped