Python | Sort list of list by specified index

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.