You can download this code by clicking the button below.
This code is now available for download.
This function is used to combine multiple iterable objects into an iterator. If the iterable objects have different lengths, fillvalue is used to fill the shorter iterable objects.
Technology Stack : itertools
Code Type : Iterator 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 be finite. Shorter iterables
supply fillvalue.
>>> list(zip_longest([1, 2, 3], 'xyz', fillvalue=-1))
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10, 11, -1]
>>> list(zip_longest([1, 2, 3, 4], 'xy', fillvalue=-1))
[1, 2, 3, 4]
[5, 6, -1, -1]
>>> list(zip_longest([1, 2, 3, 4], ['x', 'y', 'z'], fillvalue='-'))
[1, 2, 3, 4]
[5, 6, 7, '-']
>>> list(zip_longest([1, 2, 3, 4], 'xy', fillvalue=()))
[1, 2, 3, 4]
[5, 6, 7, ()]
>>> list(zip_longest([1, 2, 3, 4, 5], ['x', 'y', 'z'], fillvalue=0))
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]
"""
from itertools import zip_longest as _zip_longest
return _zip_longest(*iterables, fillvalue=fillvalue)