Categories
Python Answers

Is there a zip-like function that pads to longest length in Python?

Spread the love

Sometimes, we want to use a zip-like function that pads to longest length in Python to zip 2 lists.

In this article, we’ll look at how to use a zip-like function that pads to longest length in Python to zip 2 lists.

Is there a zip-like function that pads to longest length in Python?

To use a zip-like function that pads to longest length in Python to zip 2 lists, we can use the itertools.zip_longest method.

For instance, we write:

import itertools

a = ['a1']
b = ['b1', 'b2', 'b3']
c = ['c1', 'c2']
zipped = list(itertools.zip_longest(a, b, c))
print(zipped)

We have 3 lists a, b, and c.

Then we call itertools.zip_longest with the 3 lists.

And then we convert the iterator back to a list with list and assign the list to zipped.

Therefore, zipped is:

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

Conclusion

To use a zip-like function that pads to longest length in Python to zip 2 lists, we can use the itertools.zip_longest method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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