Python Function for Merging Iterables with FillValue

  • Share this:

Code introduction


This function uses the `itertools` and `collections` built-in libraries to merge multiple iterable objects (such as lists, tuples, etc.) into a list of tuples. If one of the iterable objects is shorter, it uses the `fillvalue` to fill in the missing values.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import Iterator
    
    # Check if all args are iterators
    iters = [iter(arg) for arg in args]
    iters = [iter(i) if isinstance(i, Iterator) else iter(list(i)) for i in iters]
    
    # Use zip_longest from itertools to zip the iterators
    zipped = zip_longest(*iters, fillvalue=fillvalue)
    
    # Convert the zipped iterator back to list
    result = [list(item) for item in zipped]
    
    return result