Last modified: Oct 31, 2024 By Alexander Williams
Python Sort a List of Tuples by One Element
Sorting a list of tuples by a specific element is a common task in Python.
This article explains methods to sort tuples by one element using sorted()
with examples.
Using sorted() with a Lambda Function
The simplest way to sort a list of tuples by one element is to use sorted()
with a lambda
function.
Specify the index of the element you want to sort by inside the lambda function.
data = [(2, 'apple'), (1, 'banana'), (3, 'cherry')]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)
[(1, 'banana'), (2, 'apple'), (3, 'cherry')]
In this example, tuples are sorted by the first element in each tuple, resulting in ascending order.
Sorting by a Different Element in the Tuple
To sort by another element, change the index in the lambda function.
This example sorts by the second element (string) in each tuple.
data = [(2, 'apple'), (1, 'banana'), (3, 'cherry')]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
[(2, 'apple'), (1, 'banana'), (3, 'cherry')]
The tuples are sorted alphabetically by the second element.
Learn more about accessing tuple elements in Accessing Elements at Index in Python Lists.
Using operator.itemgetter() for Sorting
The operator.itemgetter()
function can also be used for sorting, providing a cleaner approach.
This method is efficient for sorting large lists by specific tuple elements.
from operator import itemgetter
data = [(2, 'apple'), (1, 'banana'), (3, 'cherry')]
sorted_data = sorted(data, key=itemgetter(0))
print(sorted_data)
[(1, 'banana'), (2, 'apple'), (3, 'cherry')]
In this example, itemgetter(0)
sorts by the first element.
For more on sorting lists, see Python Sort List of Tuples: A Guide.
Sorting in Descending Order
To sort in descending order, set reverse=True
in the sorted()
function.
data = [(2, 'apple'), (1, 'banana'), (3, 'cherry')]
sorted_data = sorted(data, key=lambda x: x[0], reverse=True)
print(sorted_data)
[(3, 'cherry'), (2, 'apple'), (1, 'banana')]
In this example, tuples are sorted by the first element in descending order.
Using sort() to Sort a List of Tuples in Place
The sort()
method sorts lists in place, modifying the original list without creating a new one.
Use key
with a lambda to specify the element for sorting.
data = [(2, 'apple'), (1, 'banana'), (3, 'cherry')]
data.sort(key=lambda x: x[0])
print(data)
[(1, 'banana'), (2, 'apple'), (3, 'cherry')]
The original list data
is now sorted by the first element.
To explore more about modifying lists in Python, see Adding a List to Another List in Python.
Conclusion
Sorting lists of tuples by specific elements is straightforward in Python using sorted()
and sort()
.
Depending on your needs, you can sort in ascending, descending, or by different tuple elements.