Home >Backend Development >Python Tutorial >How to Transpose a List of Lists in Python?
Transpose a List of Lists
Given a list of lists, the goal is to transpose it, reversing the rows and columns. For instance, for the input:
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
the desired output is:
r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Python 3 Solutions:
list(map(list, zip(*l)))
This solution uses zip to iterate over the columns of the list and map to convert each column to a list.
list(map(list, itertools.zip_longest(*l, fillvalue=None)))
This solution uses itertools.zip_longest, which works similarly to zip but includes a fillvalue parameter to fill in missing values when the lists are jagged.
Python 2 Solution:
map(list, zip(*l))
Explanation:
The zip function creates an iterator of tuples, where each tuple represents a column in the input list. By unpacking the argument list with *l, zip iterates over each column in parallel. The map function then converts each tuple to a list, producing the desired transposed list.
Note: Python 2's zip does not have the fillvalue parameter, so it will discard data if the lists are jagged.
The above is the detailed content of How to Transpose a List of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!