How to transpose a list of lists in Python
In this post, I’ll explain to you how you can transpose a list of lists in Python.
Transpose
Before going deeper let me first explain about transpose so transpose is defined as the interchanging of rows and columns.
List in Python
List in Python is the type of variable in which we can store multiple values. Or we can say that List is like an array but the list has one advantage over an array we can put any data type value in a single list whether it is off integer or string.
We declare the list as below:-
l=[] #it is an empty list l1=['Mohit',68,'Rohit'] #l1 is the list which consist three values print(l1)
Output
['Mohit', 68, 'Rohit']
The list is mutable it means we can change it or modify it after its declaration.
For more information about the list refer to python.org documentation/tutorials.
List of Lists
List of Lists means when a list consists of another list inside it. Or we can say it is a two-dimensional list.
As below:-
#list of lists l=[[1,2,3],[1]] #l is contains another list inside it print(l)
Output
[[1, 2, 3], [1]]
Transpose a List of Lists
Now, to transpose a list of lists we can use various methods like zip() function, using for loop and using NumPy library.
Here below I’ll discuss with you the two most common and easiest methods to do it.
1. Using for loop in Python
Using for loop we can transpose a list of lists as below:-
# python program to transpose a list of lists using loop # declare a list of lists l1 = [[6, 4, 3], [5, 4, 5], [9, 6, 4]] l2 = [] # l2 is an empty list we declare it to store transpose of above list # now we'll declare a function to transpose the lists def transpose(l1, l2): # iterate over the list #len python is use for finding the length of the list for i in range(len(l1[0])): row = [] #to print values for j in l1: # appending to new list with values and index number # j contains values and i contains index position row.append(j[i]) l2.append(row) #appending value of row list into l2 which is an empty list return l2 # printing transpose print(transpose(l1, l2))
Output:- [[6, 5, 9], [4, 4, 6], [3, 5, 4]]
2. Using NumPy
It is an easy way to transpose the list of lists than the above for loop method:-
NumPy is a Python library that handles multi-dimensional arrays and matrices operations.
For more information about NumPy refer to the:-https://numpy.org/
#Python program to transpose the list using NumPy #first we need to import python NumPy library as below import numpy as np #now declare a list of lists l1=[[4,7,6],[5,2,4],[8,3,4]] print(np.transpose(l1)) #it tranpose the lists
Output
[[4 5 8] [7 2 3] [6 4 4]]
As you have seen using NumPy we can easily do it. It is a more efficient and easy way than the loop.
Leave a Reply