Variable Length Tuple Combination with Fillvalue

  • Share this:

Code introduction


This function combines a variable number of arguments into tuples. If the lengths of some arguments are inconsistent, it fills the shorter arguments with fillvalue until all arguments are of the same length.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest

    def _zip_longest(*args, fillvalue):
        iterator = zip_longest(*args, fillvalue=fillvalue)
        while True:
            try:
                yield next(iterator)
            except StopIteration:
                return

    return _zip_longest(*args, fillvalue=fillvalue)                
              
Tags: