You can download this code by clicking the button below.
This code is now available for download.
The function merges multiple iterable objects into a single iterator. If the iterables have different lengths, the `fillvalue` is used to fill in the missing parts.
Technology Stack : itertools
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*iterables, fillvalue=None):
"Make an iterator that aggregates elements from each of the iterables.
The iterables must have the same length or the shortest iterable is repeated
until the longest is exhausted. The iterator stops when the longest iterable is exhausted.
Parameters
----------
iterables : one or more iterables
An empty iterable will result in the end of iteration for the entire iterator.
A non-empty iterable will result in the end of iteration when the iterator is exhausted.
fillvalue : value, optional
Value to use for missing values if the iterables are of unequal length. Defaults to None.
Examples
--------
>>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue=0))
[(1, 4, 6), (2, 5, None), (3, None, None)]
>>> list(zip_longest([1, 2, 3, 4], [5, 6], fillvalue=0))
[(1, 5, 0), (2, 6, 0), (3, None, 0), (4, None, 0)]
>>> list(zip_longest([1, 2, 3], [4, 5, 6], [7, 8, 9], fillvalue=0))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> list(zip_longest('abc', 'de', fillvalue='-'))
[('a', 'd', '-'), ('b', 'e', '-'), ('c', None, '-')]
>>> list(zip_longest('abc', 'd', fillvalue='-'))
[('a', 'd', '-'), ('b', None, '-'), ('c', None, '-')]
"
from itertools import zip_longest
return list(zip_longest(*iterables, fillvalue=fillvalue))