How to Sort Tuples in Python

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.

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.

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.

The output would be:

[(3, 'apple'), (2, 'banana'), (1, 'cherry')]

The full code:

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.