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)
Output:
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
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)
Output:
[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
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)
Output:
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
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!