Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Sort list of list by specified index

Improve Article
Save Article
  • Last Updated : 12 Sep, 2022
Improve Article
Save Article

We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let’s discuss certain ways in which this task can be performed using Python.

Method 1: Sort list of lists using sort() + lambda

The anonymous nature of Python Lambda Functions indicates that they lack a name. The Python sort() can be used to perform this variation of sort by passing a function. The list can be sorted using the sort function both ascendingly and descendingly. 

Python3




# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# sort list of list
# sort by second index
test_list.sort(key = lambda test_list: test_list[1])
 
# printing result
print ("List after sorting by 2nd element of lists : " + str(test_list))

Output :

The original list is : [[‘Rash’, 4, 28], [‘Varsha’, 2, 20], [‘Nikhil’, 1, 20], [‘Akshat’, 3, 21]]

List after sorting by 2nd element of lists : [[‘Nikhil’, 1, 20], [‘Varsha’, 2, 20], [‘Akshat’, 3, 21], [‘Rash’, 4, 28]]

Method 2: Sort a list of lists using sorted() + itemgetter() 

The Itemgetter can be used instead of the lambda function to achieve similar functionality. itemgetter() is used to get the index element by which the sort operation needs to be performed.  

Python3




from operator import itemgetter
 
# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20],
             ['Nikhil', 1, 20], ['Akshat', 3, 21]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# sort list of list
# sort by second index
res = sorted(test_list, key = itemgetter(1))
 
# printing result
print ("List after sorting by 2nd element of lists : " + str(res))

Output :

The original list is : [[‘Rash’, 4, 28], [‘Varsha’, 2, 20], [‘Nikhil’, 1, 20], [‘Akshat’, 3, 21]]

List after sorting by 2nd element of lists : [[‘Nikhil’, 1, 20], [‘Varsha’, 2, 20], [‘Akshat’, 3, 21], [‘Rash’, 4, 28]]


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!