Python itertools.zip_longest() Function



The Python itertools.zip_longest() function is used to iterate over multiple iterables in parallel, filling in missing values with a specified default when iterables of different lengths are provided.

This function is useful when working with sequences of unequal lengths while ensuring all elements are processed.

Syntax

Following is the syntax of the Python itertools.zip_longest() function −

itertools.zip_longest(*iterables, fillvalue=None)

Parameters

This function accepts the following parameters −

  • *iterables: Two or more iterables to be zipped together.
  • fillvalue (optional): The value to fill missing elements when iterables have different lengths (default is None).

Return Value

This function returns an iterator that aggregates elements from each iterable, filling missing values where necessary.

Example 1

Following is an example of the Python itertools.zip_longest() function. Here, we zip two lists of different lengths −

import itertools

list1 = [1, 2, 3]
list2 = ['a', 'b']

result = itertools.zip_longest(list1, list2, fillvalue='X')
for item in result:
   print(item)

Following is the output of the above code −

(1, 'a')
(2, 'b')
(3, 'X')

Example 2

Here, we zip three lists with different lengths and specify a custom fill value −

import itertools

list1 = [10, 20, 30, 40]
list2 = ['A', 'B']
list3 = [100, 200, 300]

result = itertools.zip_longest(list1, list2, list3, fillvalue='-')
for item in result:
   print(item)

Output of the above code is as follows −

(10, 'A', 100)
(20, 'B', 200)
(30, '-', 300)
(40, '-', '-')

Example 3

Now, we use itertools.zip_longest() function to align data from multiple sequences while ensuring all elements are included −

import itertools

months = ["Jan", "Feb", "Mar"]
sales = [1000, 1500]

result = itertools.zip_longest(months, sales, fillvalue=0)
for month, sale in result:
   print(f"Month: {month}, Sales: {sale}")

The result obtained is as shown below −

Month: Jan, Sales: 1000
Month: Feb, Sales: 1500
Month: Mar, Sales: 0

Example 4

When working with CSV files, the itertools.zip_longest() function can be used to ensure uniform row lengths by padding missing values −

import itertools

data1 = ["Alice", "Bob"]
data2 = [25, 30, 35]
data3 = ["Engineer", "Doctor"]

result = itertools.zip_longest(data1, data2, data3, fillvalue="N/A")
for row in result:
   print(row)

The result produced is as follows −

('Alice', 25, 'Engineer')
('Bob', 30, 'Doctor')
('N/A', 35, 'N/A')
python_modules.htm
Advertisements