Last modified: Jul 03, 2023 By Alexander Williams
Sorting a List of Tuples by First and Second Element in Python
A list of tuples is a list contains a collection of tuples, for example:
[(4, 8, 6), (7, 3, 9), (1, 1, 3)]
This article will guide you through sorting a list of tuples by the first and second elements.
Table Of Contents
Sorting by First Element
You can use the sorted() function with a lambda function as the key To sort a list of tuples by the first element.
Here is an example:
data = [('banana', 3), ('apple', 2), ('orange', 5)]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)
Output:
[('apple', 2), ('banana', 3), ('orange', 5)]
As you can see, The key
parameter is set to a lambda function that extracts the first element (x[0]
) from each tuple.
Sorting by Second Element
To sort the list of tuples by the second element, you can modify the lambda function to access the second element (x[1]
). Here's an example:
data = [('banana', 3), ('apple', 2), ('orange', 5)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
Output:
[('apple', 2), ('banana', 3), ('orange', 5)]
Sorting by Multiple Elements
You can also sort by multiple elements using a tuple as the key. You can see the below example.
data = [('banana', 3), ('apple', 2), ('orange', 5)]
sorted_data = sorted(data, key=lambda x: (x[0], x[1]))
print(sorted_data)
The sorting process will prioritize the first and, subsequently, the second elements.
Output:
[('apple', 2), ('banana', 3), ('orange', 5)]
Conclusion
Here, we have learned how to sort a list of tuples by first, second element, and multiple elements using the sorted()
function.