You can download this code by clicking the button below.
This code is now available for download.
This function is similar to the built-in zip function, but it allows for iterables of unequal length. When the shortest iterable is exhausted, the fillvalue is used to fill in missing values in the longer iterables.
Technology Stack : itertools
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*iterables, fillvalue=None):
"zip_longest(*iterables, fillvalue=None) -> zip_longest object
Make an iterator that aggregates elements from each of the iterables.
The iterator returns pairs of elements, one from each iterable. The shortest
iterable is repeated until the longest is exhausted.
Parameters
----------
*iterables : iterables
An arbitrary number of iterables.
fillvalue : value, optional
The value to use for missing values if the iterables are of unequal length.
Examples
--------
>>> list(zip_longest('ABCD', 'xy', fillvalue='-'))
[('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')]
>>> list(zip_longest('saw', 'pad', fillvalue='*'))
[('s', 'p'), ('a', 'a'), ('w', '*'), ('-', '*')]
>>> list(zip_longest(range(3), repeat(10), fillvalue=0))
[(0, 0, 0), (1, 1, 1), (2, 2, 2), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]
"""
from itertools import zip_longest
return zip_longest(*iterables, fillvalue=fillvalue)