A list is a data structure that stores multiple objects in a single variable. It is also mutable and creates ordered elements. If you want to transpose a list of lists in Python then this post is for you. In this tutorial, you will learn the various methods to Transpose a List of Lists in Python.
Methods to Transpose a List of Lists in Python
To transpose a list of lists in Python, you can use multiple methods. Below are the different approaches to find the transpose.
Method 1: Using Nested List Comprehension
You can use nested list comprehension to transpose the list of lists.
original_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
transposed_list = [[original_list[j][i] for j in range(len(original_list))] for i in range(len(original_list[0]))]
print(transposed_list)
Output
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Method 2: Using the zip() function
You can use the built-in zip()
function along with the unpacking operator (*
) to transpose the list of lists. Use the below lines of code.
original_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
transposed_list = list(map(list, zip(*original_list)))
print(transposed_list)
Output
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Method 3: Using the numpy library
If you have the Numpy library installed, you can use it to transpose the list of lists.
import numpy as np
original_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
transposed_list = np.transpose(original_list).tolist()
print(transposed_list)
Output
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Method 4: Using a loop
You can also use a loop to transpose the list of lists.
original_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
transposed_list = []
for i in range(len(original_list[0])):
transposed_row = []
for j in range(len(original_list)):
transposed_row.append(original_list[j][i])
transposed_list.append(transposed_row)
print(transposed_list)
Output
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Method 5: Using the pandas library
If you have the pandas library installed, you can use its DataFrame to transpose the list of lists.
import pandas as pd
original_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
df = pd.DataFrame(original_list)
transposed_list = df.transpose().values.tolist()
print(transposed_list)
Output
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Conclusion
Many coders use Python List to store multiple variables in a single variable. In this tutorial you have learned how to transpose a list of lists in different methods like numpy, pandas, loop, nested list comprehension, etc You can use any method you want.
Leave a Reply