Categories
Python Answers

How to transpose a list of lists with Python?

Spread the love

Sometimes, we want to transpose a list of lists with Python.

In this article, we’ll look at how to transpose a list of lists with Python.

How to transpose a list of lists with Python?

To transpose a list of lists with Python, we can use the map function with the itertools.zip_longest method.

itertools.zip_longest lets us transpose any nested arrays including jagged ones.

For instance, we write:

import itertools

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
t = list(map(list, itertools.zip_longest(*l, fillvalue=None)))
print(t)

We call map with list and the array created by itertools.zip_longest which takes the item from each nested array and returned.

fillvalue is set to None so that lists that are shorter than the longest one in the list will have None added to them so that they match the length of the longest list.

Then we call list to convert the returned map with the transposed nested lists back to a nested list.

Therefore, t is [[1, 4, 7], [2, 5, 8], [3, 6, 9]].

Conclusion

To transpose a list of lists with Python, we can use the map function with the itertools.zip_longest method.

itertools.zip_longest lets us transpose any nested arrays including jagged ones.

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 *