zip_longest: Handling Iterables of Different Lengths in Python

When working with iterables in Python, you may need to aggregate elements from multiple iterables. The built-in zip function can do this, but it stops when the shortest iterable is exhausted, potentially omitting pairs of elements if the iterables have different lengths.

Let’s consider an example:

fruits = ["apple", "orange", "grape"]
prices = [1, 2]

If we use zip to aggregate these iterables, we’ll get:

list(zip(fruits, prices))

Output:

[('apple', 1), ('orange', 2)]

As you can see, the third element of the fruits iterable (“grape”) is not included in the output because there is no corresponding element in the prices iterable.

To overcome this limitation, we can use the zip_longest function from the itertools module. This function aggregates iterables of different lengths by filling missing values with a specified fillvalue.

Here’s how we can use zip_longest to aggregate our fruits and prices iterables:

from itertools import zip_longest

list(zip_longest(fruits, prices, fillvalue="-"))

Output:

[('apple', 1), ('orange', 2), ('grape', '-')]

In this example, the fillvalue is set to "-", which means that missing values in the prices iterable are replaced with a hyphen.

Related Posts

Leave a Comment

Your email address will not be published. Required fields are marked *

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran