Open In App

Python program to Sort a list according to the second element of sublist

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with lists of lists, there are times when we need to sort the sublists by the second element. This is common when organizing data, such as sorting a list of employees by their ages or scores. The easiest way to sort a list by the second element of each sublist is by using the sorted() function with a lambda function as the key. The lambda function lets us specify which element in the sublist to focus on while sorting.

Python
a = [[1, 3], [2, 1], [4, 2], [3, 5]]

# Sorts by the second element
a = sorted(a, key=lambda x: x[1])  
print(a)  

Output
[[2, 1], [4, 2], [1, 3], [3, 5]]

Other methods that we can use to sort a list according to the second element of sublist in Python are:

Using itemgetter() from operator module

Another way to sort is by using itemgetter() from Python’s operator module. It allows us to specify which element in the sublist to use for sorting. This method can be a bit more efficient for larger datasets.

Python
from operator import itemgetter

a = [[1, 3], [2, 1], [4, 2], [3, 5]]

 # Sorts by the second element
a = sorted(a, key=itemgetter(1)) 
print(a)  

Output
[[2, 1], [4, 2], [1, 3], [3, 5]]

Using sort() Method

If we don’t need a new list and prefer to sort the list in place, we can use the sort() method. It directly modifies the list we’re working with instead of creating a new one.

Python
a = [[1, 3], [2, 1], [4, 2], [3, 5]]

 # Sorts in place by the second element
a.sort(key=lambda x: x[1]) 
print(a)  

Output
[[2, 1], [4, 2], [1, 3], [3, 5]]

Using operator.attrgetter()

If the sublists contain objects or named tuples, you can use operator.attrgetter() to sort based on an attribute. This method is not typically used for simple lists, but it’s handy when working with more complex structures.

Python
from operator import attrgetter

class Item:
    def __init__(self, a, b):
        self.a = a
        self.b = b

a = [Item(1, 3), Item(2, 1), Item(4, 2), Item(3, 5)]
 # Sorts by the second element (attribute b)
a = sorted(a, key=attrgetter('b')) 
print([[i.a, i.b] for i in a])  

Output
[[2, 1], [4, 2], [1, 3], [3, 5]]

Using a Custom Comparison Function

To use a custom comparison function for sorting, you can use cmp_to_key from the functools module. This is a more advanced method but allows for more control over how the sorting is done.

Python
from functools import cmp_to_key

def compare_second_element(x, y):
   # Compare based on the second element
    return x[1] - y[1] 

a = [[1, 3], [2, 1], [4, 2], [3, 5]]
# Sort in place by the second element
a.sort(key=cmp_to_key(compare_second_element))  
print(a) 

Output
[[2, 1], [4, 2], [1, 3], [3, 5]]


Practice Tags :

Similar Reads