Sort a List of Tuples by Second Item - Python
The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)], the goal is to reorder it by the second item, resulting in [(4, 1), (2, 2), (1, 3)].
Using sorted()
sorted() is the most versatile way to sort data. It takes an iterable and returns a new sorted list without modifying the original list. We can specify the sorting key using the key parameter which allows us to sort the tuples based on the second item.
a = [(1, 3), (4, 1), (2, 2)]
# Sort the list based on the second element
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.
Table of Content
Using sort()
Unlike sorted(), the sort() method sorts the list in place meaning it directly modifies the original list without returning a new one. This method is more efficient when we do not need to preserve the original list order.
a = [(5, 2), (1, 6), (3, 4)]
# Sort the list in-place based on the second element
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 itemgetter
itemgetter() from the operator module provides a more efficient and readable way to retrieve the sorting key. It is often faster than using a lambda function, especially for larger datasets.
from operator import itemgetter
a = [(7, 5), (3, 8), (2, 6)]
# Sort the list based on the second element
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.