Skip to content
Related Articles

Related Articles

Python | Sort list of list by specified index
  • Last Updated : 23 Dec, 2018

We can sort list of list using the conventional sort function. This sorts the list by the first index of lists. But more than often there can be circumstances that requires the sorting of list of list by other index elements than first. Lets discuss certain ways in which this task can be performed.

Method #1 : Using sort() + lambda
sort() can be used to perform this variation of sort by passing a function as a key that performs the sorting according to the desired inner list index.




# Python 3 code to demonstrate 
# to sort list of list by given index 
# using sort() + lambda
  
  
# 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))
  
# using sort() + lambda
# to 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 : Using sorted() + itemgetter()
This can also be applied to perform this particular task. The advantage that it holds is that it does not modify the original list. itemgetter() is used to get the index element by which the sort operation needs to be performed.




# Python3 code to demonstrate 
# to sort list of list by given index 
# using sorted() + itemgetter()
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))
  
# using sort() + lambda
# to 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]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :