Python Implementation of itertools.zip_longest

  • Share this:

Code introduction


The function implements the functionality of itertools.zip_longest, which is used to concatenate elements from each of the iterable objects. If the iterables are of uneven length, missing values are filled in with fillvalue.


Technology Stack : itertools, collections, operator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # zip_longest function is used to create an iterator that aggregates elements from each of the iterables.
    # If the iterables are of uneven length, missing values are filled-in with fillvalue.

    from itertools import zip_longest
    from itertools import islice
    from collections import deque
    from operator import itemgetter

    def interleave(zipped, fillvalue):
        for i, v in zip_longest(*zipped, fillvalue=fillvalue):
            if v is fillvalue:
                continue
            yield v

    # Find the longest iterable
    max_length = max(len(x) for x in args)
    
    # Create a deque for each iterable and fill them with the fillvalue
    deques = [deque(fillvalue=fillvalue) for _ in args]
    
    # Iterate over the longest iterable
    for i in range(max_length):
        # Get the item from each deque if it exists
        items = [deque[i] for deque in deques if i < len(deque)]
        
        # If not all deques have the same item at position i, fill with the fillvalue
        items = [item if item is not fillvalue else fillvalue for item in items]
        
        # Interleave the items
        for item in interleave(zip(items), fillvalue):
            yield item

    # Clean up the remaining elements in the deques
    for deque in deques:
        for item in deque:
            yield item