Home >Backend Development >Python Tutorial >How to Sort a List of Tuples by Their Integer Values?
Sorting a List of Tuples by Second Item (Integer Value)
You have provided a list of tuples in the format [('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)]. You seek to sort this list in ascending order based on the integer values within the tuples.
To achieve this sorting, leverage the key keyword argument in the sorted() function. By default, it sorts in increasing order. Here's the solution:
sorted([('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], key=lambda x: x[1])
The key parameter accepts a function that retrieves the comparable element from your data structure. In this case, it is the second element of the tuple, so we reference it as x[1].
For improved performance, consider using operator.itemgetter(1) as suggested by jamylak. It is essentially a faster version of lambda x: x[1].
The above is the detailed content of How to Sort a List of Tuples by Their Integer Values?. For more information, please follow other related articles on the PHP Chinese website!