Python Zip Longest Function with Fillvalue

  • Share this:

Code introduction


This function accepts any number of iterable arguments and returns an iterator that 'fills' shorter iterables to match the length of the longest iterable using a `fillvalue`. If all iterables are of the same length, it returns an iterator of tuples directly.


Technology Stack : itertools, collections, bisect, array, heapq, random, string, math, datetime, functools, operator

Code Type : Function

Code Difficulty : Advanced


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from collections import deque
    from bisect import bisect_left
    from array import array
    from heapq import heapify, heappush, heappop
    from random import choice, seed, randrange
    from string import ascii_letters, digits
    from math import factorial, sqrt, pi
    from datetime import datetime, timedelta
    from functools import reduce, lru_cache
    from operator import mul, add

    def generate_combinations(items, n):
        for i in range(len(items) - n + 1):
            yield tuple(items[i:i + n])

    def median(lst):
        sorted_lst = sorted(lst)
        lst_len = len(lst)
        index = (lst_len - 1) // 2

        if lst_len % 2:
            return sorted_lst[index]
        else:
            return (sorted_lst[index] + sorted_lst[index + 1]) / 2.0

    def fibonacci(n):
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a

    def is_prime(num):
        if num < 2:
            return False
        for i in range(2, int(sqrt(num)) + 1):
            if num % i == 0:
                return False
        return True

    return zip_longest(*args, fillvalue=fillvalue)