Home > Backend Development > Python Tutorial > How Can I Pad Zipped Lists in Python to Match the Longest Length?

How Can I Pad Zipped Lists in Python to Match the Longest Length?

Barbara Streisand
Release: 2024-11-28 07:30:13
Original
611 people have browsed it

How Can I Pad Zipped Lists in Python to Match the Longest Length?

Padding Zipped Lists to Longest Length

In the realm of Python programming, the zip() function seamlessly merges multiple iterables into a list of tuples. However, the length of the resultant list is often constrained by the shortest input. To overcome this limitation and pad the list to the length of the longest input, one might seek alternative solutions.

itertools.zip_longest: The Perfect Fit

Python 3 unveils the power of itertools.zip_longest, a function specifically designed for this purpose. It seamlessly pads the shorter inputs with None values, effectively extending the list to the length of the longest iterable.

Here's an illustrative example:

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

result = list(itertools.zip_longest(a, b, c))

print(result)
Copy after login

Output:

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

Customizing the Padding Value

The zip_longest function offers the flexibility to specify a custom padding value using the fillvalue parameter. This allows for more control over the padding mechanism.

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

print(result)
Copy after login

Output:

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

Python 2.x: Alternative Approaches

For Python 2.x users seeking an equivalent solution, they can utilize itertools.izip_longest (available in Python 2.6 ) or employ map with None as an alternative.

result = list(map(None, a, b, c))

print(result)
Copy after login

Output:

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

The above is the detailed content of How Can I Pad Zipped Lists in Python to Match the Longest Length?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template