Flatten Merged Iterables with FillValue Using itertools.zip_longest

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to merge multiple iterable objects, filling missing values with a specified fill value if their lengths are unequal. Then, it uses `operator.itemgetter` and `collections.defaultdict` to extract and flatten the result list.


Technology Stack : itertools, operator, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from operator import itemgetter
    from collections import defaultdict

    # The zip_longest function from itertools is used to pair up elements from
    # multiple iterables, filling missing values with a specified fillvalue
    # if the iterables are of unequal length.
    def _pair_up(iterables):
        return zip_longest(*iterables, fillvalue=fillvalue)

    # The itemgetter from operator is used to extract multiple items from a
    # single iterable using their names.
    # defaultdict from collections is used to create a dictionary that
    # defaults to a specified type when a key is not found.

    def _flatten_list_of_tuples(tuples_list):
        result = []
        for tup in tuples_list:
            result.extend(tup)
        return result

    # First, we zip the input iterables to create a list of tuples.
    tuples_list = _pair_up(args)

    # Then, we flatten the list of tuples to get a single list.
    flattened_list = _flatten_list_of_tuples(tuples_list)

    return flattened_list