Home >Backend Development >Python Tutorial >How to Sort a List of Tuples by Their Integer Values?

How to Sort a List of Tuples by Their Integer Values?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 18:31:15814browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn