Python `zip_longest` Function Explanation

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to handle iterables of unequal lengths. When one iterable ends, `fillvalue` is used to fill in the remaining values so that all tuples are of the same length.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    # This function will return a list of tuples, where the tuples have a length equal to the longest input iterable.
    # If input iterables are of unequal lengths, missing values in shorter iterables will be filled with `fillvalue`.
    from itertools import zip_longest as it_zip_longest
    return list(it_zip_longest(*args, fillvalue=fillvalue))                
              
Tags: