Home >Backend Development >Python Tutorial >How to Sort a List of Tuples by Their Integer Second Item in Python?
Sorting Tuples by Second Item (Integer Value)
Sorting a list of tuples by the second item, an integer value, can be achieved using Python's built-in sorted() function. The key keyword argument allows you to specify a function that retrieves the comparable element from each tuple.
Solution:
sorted_tuples = sorted( [('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], key=lambda x: x[1] )
In this example, lambda x: x[1] is a function that extracts the second item from a tuple. sorted() sorts the list by ascending order of this second item.
Optimization:
For improved performance, you can use operator.itemgetter(1) as the key instead of lambda. itemgetter() is a more optimized way to retrieve a specific item from a tuple.
from operator import itemgetter sorted_tuples = sorted( [('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], key=itemgetter(1) )
The above is the detailed content of How to Sort a List of Tuples by Their Integer Second Item in Python?. For more information, please follow other related articles on the PHP Chinese website!