Sort a List of Tuples by Second Item - Python
Last Updated :
25 Oct, 2025
Given a list of tuples, the task is to sort them based on their second element. Each tuple holds ordered data and sorting them by the second item helps organize values in a meaningful order.
For example:
Input: [(1, 3), (4, 1), (2, 2)]
Output: [(4, 1), (2, 2), (1, 3)]
Let’s explore different methods to perform this sorting efficiently in Python.
Using itemgetter
itemgetter() from the operator module directly fetches the second item (index 1) from each tuple, making sorting efficient for large datasets.
Python
from operator import itemgetter
a = [(7, 5), (3, 8), (2, 6)]
res = sorted(a, key=itemgetter(1))
print(res)
Output[(7, 5), (2, 6), (3, 8)]
Explanation: itemgetter(1) retrieves the second item (1) from each tuple. It is more efficient than using a lambda function and sorted() sorts the list based on the second item of each tuple.
Using sorted() with Lambda
The sorted() function can also use a lambda function as the sorting key. It extracts the second element from each tuple during comparison and returns a new sorted list.
Python
a = [(1, 3), (4, 1), (2, 2)]
res = sorted(a, key=lambda x: x[1])
print(res)
Output[(4, 1), (2, 2), (1, 3)]
Explanation: sorted(a, key=lambda x: x[1]) extract the second element (x[1]) from each tuple for comparison and list is returned in sorted order by the second item of each tuple.
Using sort() with lambda
If you don’t need to preserve the original list, you can use the sort() method, which modifies the list in place. It saves memory since no new list is created.
Python
a = [(5, 2), (1, 6), (3, 4)]
a.sort(key=lambda x: x[1])
print(a)
Output[(5, 2), (3, 4), (1, 6)]
Explanation: a.sort(key=lambda x: x[1]) sorts the list a in place based on the second item of each tuple and result is directly stored in the original list a and no new list is created.
Using heapq.nsmallest()
If you only need the smallest or largest tuples based on the second item, use the heapq module. This avoids sorting the entire list ideal for large datasets when only a few results are needed.
Python
import heapq
a = [(1, 3), (4, 1), (2, 2)]
res = heapq.nsmallest(len(a), a, key=lambda x: x[1])
print(res)
Output[(4, 1), (2, 2), (1, 3)]
Explanation: heapq.nsmallest() finds smallest tuples based on the key efficiently. It uses a heap internally, reducing unnecessary comparisons.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice