In Python, tuples are used to keep multiple elements as a single variable. Tuples are ordered and immutable, allowing duplicate values.
However, when working with tuples, you might sometimes want to sort them either based on the first element or based on the second element. This post will guide you on how to sort tuples in Python in different ways.
1. Basic Sorting of Tuples
Python’s built-in sorted() function can be used directly on your list of tuples. This function sorts the tuples by the first element in the tuple.
1 2 3 4 5 |
# list of tuples t_list = [(3, 'apple'), (2, 'banana'), (1, 'cherry')] # sort list of tuples sorted_list = sorted(t_list) print(sorted_list) |
You would get the following output:
[(1, 'cherry'), (2, 'banana'), (3, 'apple')]
2. Sorting Tuples by the Second Element
In order to sort the tuple by the second element, you need to use a custom sorting function with the sorted function.
1 2 3 4 5 6 7 |
# function to get the second element of tuple def secondElement(element): return element[1] # sort using a function sorted_list = sorted(t_list, key=secondElement) print(sorted_list) |
This code will produce the following output:
[(3, 'apple'), (2, 'banana'), (1, 'cherry')]
3. Sorting Tuples in Reverse Order
Python’s sorted function also allows you to sort the tuples in reverse order by setting the “reverse” parameter to True.
1 2 3 |
# sort in reverse order sorted_list = sorted(t_list, reverse=True) print(sorted_list) |
The output would be:
[(3, 'apple'), (2, 'banana'), (1, 'cherry')]
The full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# list of tuples t_list = [(3, 'apple'), (2, 'banana'), (1, 'cherry')] # sort list of tuples sorted_list = sorted(t_list) print(sorted_list) # function to get the second element of tuple def secondElement(element): return element[1] # sort using a function sorted_list = sorted(t_list, key=secondElement) print(sorted_list) # sort in reverse order sorted_list = sorted(t_list, reverse=True) print(sorted_list) |
Conclusion
In conclusion, Python provides several ways to sort tuples, either directly or using a custom sorting function. You can also sort tuples in reverse order. This concept is useful in a number of situations such as data manipulation, problem-solving, etc.