Home >Backend Development >Python Tutorial >How Does Python\'s `zip_longest()` Function Handle Unequal-Length Input Sequences?

How Does Python\'s `zip_longest()` Function Handle Unequal-Length Input Sequences?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 04:14:09875browse

How Does Python's `zip_longest()` Function Handle Unequal-Length Input Sequences?

Extending Zip Functionality with Padding

Zip() is a useful function for combining elements from multiple sequences into a single list of tuples. However, it has a limitation in that it will only create tuples with as many elements as the shortest input sequence. This can lead to incomplete results when working with sequences of varying lengths.

To overcome this limitation, a more advanced function called zip_longest() has been introduced. zip_longest() is available in Python 3, and it provides an enhanced version of zip() that automatically pads missing values in the results so that the length of the resultant list matches the length of the longest input rather than the shortest.

To use zip_longest(), simply pass it the sequences you want to combine as arguments. The function will create tuples for each set of corresponding elements in the input sequences, and it will fill in any missing values with a default padding value (usually None).

For example, consider the following code snippet:

a = ['a1']
b = ['b1', 'b2', 'b3']
c = ['c1', 'c2']

print(list(itertools.zip_longest(a, b, c)))

This code will output the following list of tuples:

[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

As you can see, the resultant list has the same length as the longest input sequence (b). The missing values in a and c have been padded with None.

You can also specify a custom padding value using the fillvalue parameter. For example, the following code snippet pads missing values with the string 'foo':

print(list(itertools.zip_longest(a, b, c, fillvalue='foo')))

This will output the following list of tuples:

[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]

The above is the detailed content of How Does Python\'s `zip_longest()` Function Handle Unequal-Length Input Sequences?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn