Home >Backend Development >Python Tutorial >How to Efficiently Sort Python Tuples by Their Integer Second Element?
When working with lists of tuples containing both string and integer elements, sorting them efficiently based on the integer values can be essential. This article delves into a solution for this common programming task.
To sort a list of tuples by their second item, which is an integer, we can utilize the sorted() function in Python. This function allows for customization of sorting criteria using the key keyword argument.
The key argument takes a function as input, which determines how the tuples should be compared. In this case, we want to compare them based on their second element. We can define a custom function using lambda syntax as follows:
lambda x: x[1]
This function takes a single tuple as input and returns its second element.
Now, we can use the key argument in sorted() to specify this custom function as the sorting rule:
sorted([('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], key=lambda x: x[1])
This will return a new list containing the tuples sorted in ascending order by their second element:
[('abc', 121), ('abc', 148), ('abc', 221), ('abc', 231)]
For optimal performance, consider using operator.itemgetter(1) instead of lambda x: x[1]. Operator.itemgetter is a built-in function explicitly designed for extracting the specified element from a data structure, which can improve efficiency.
from operator import itemgetter sorted([('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], key=itemgetter(1))
This approach achieves the same result as using the lambda function but may be slightly faster in some cases.
The above is the detailed content of How to Efficiently Sort Python Tuples by Their Integer Second Element?. For more information, please follow other related articles on the PHP Chinese website!