Home >Backend Development >Python Tutorial >How Can I Transpose a List of Lists in Python?
Transposing a List of Lists
Given a list of lists, such as:
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Our goal is to transpose the list, resulting in:
r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Using zip
The zip() function in Python combines elements from multiple iterables into a single list of tuples. We can use zip to create a transposed list by passing the original list as a sequence of arguments:
result = list(map(list, zip(*l)))
The outer list() converts the tuples into lists, and the map() function applies this transformation to each element in the zip result.
Using zip_longest
The itertools.zip_longest() function is similar to zip, but it does not discard data if the iterables have different lengths. It fills shorter iterables with a specified fillvalue (None by default):
from itertools import zip_longest result = list(map(list, zip_longest(*l, fillvalue=None)))
Explanation
The key to transposition is the use of zip to combine elements from the original list's sublists. The zip() function generates tuples containing one element from each sublist at the same index. These tuples are then converted into lists to create the rows of the transposed list.
By using the * operator to unpack the original list as arguments to zip, we can transpose the list in a single line of code. The map() function is used to ensure that the result is a list of lists.
The above is the detailed content of How Can I Transpose a List of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!