What is the itertools.zip_longest module in Python?

Overview

Itertools is a module in Python that enables fast, and memory-efficient iteration over iterable data structures.

The module has a number of functions that construct and return iterators. One such function is the zip_longest function. This function makes an iterator that aggregates elements from each of the iterables. The iteration continues until the longest iterable is not exhausted.

Syntax

zip_longest(*iterables, fillvalue=None)

This function takes two arguments:

  • iterables: This is the data structure(s) over which we want to iterate.

  • fillvalue: This is the value that we want to fill in the case where iterables are of uneven length.

Return value

The function returns the aggregated data structure.

Example

import itertools
x =[1, 2, 3, 4, 5, 6, 7]
y =[8, 9, 10]
a = [12,13,14]
z = list(itertools.zip_longest(x, y, a, fillvalue = 'a'))
print("Aggregated List:",z)

Explanation

  • Lines 4–6: We create three lists x, y, and a. The longest list is x, because it contains the most number of elements.
  • Line 7: We call the zip_longest function, which aggregates each item in the provided lists. We also provide the fillvalue as a.

The output list shows the aggregated list where the missing values in the smaller lists are filled with a.

Free Resources