Python – Sort a Tuple
To sort a Tuple in Python, use sorted() builtin function. Pass the tuple as argument to sorted() function. The function returns a list with the items of tuple sorted in ascending order. We may convert this list to tuple using
tuple().
We can also specify the sorting order via reverse parameter to sorted() function. The default sorting order is ascending. reverse=True
sorts the items in descending order.
Also, we can specify a key function, based on whose returned values, sorting of items is done.
Python sorted() builtin function
Examples
1. Sort a Tuple of Integers
In the following program, we take a tuple x
with integer values, and sort this tuple in ascending order.
Python Program
aTuple = (2, 5, 8, 1, 9, 3, 7)
result = sorted(aTuple)
result = tuple(result)
print('Sorted Tuple :', result)
Output
Sliced Tuple : (1, 2, 3, 5, 7, 8, 9)
2. Sort a Tuple in Descending Order
To sort in descending order, pass reverse=True
to sorted() function.
Python Program
aTuple = (2, 5, 8, 1, 9, 3, 7)
result = sorted(aTuple, reverse=True)
result = tuple(result)
print('Sorted Tuple :', result)
Output
Sorted Tuple : (9, 8, 7, 5, 3, 2, 1)
3. Slice a Tuple based on Key Function
A key is a function that takes a value and returns a value. For each of the items in tuple, this key function is applied, and the returned value is used for comparison to sort the items.
In the following program, we sort tuple of strings based on the length of strings. For this case, we may use len() builtin function as key.
Python Program
aTuple = ('abc', 'mn', 'pqrs')
result = sorted(aTuple, key=len)
result = tuple(result)
print('Sorted Tuple :', result)
Output
Sorted Tuple : ('mn', 'abc', 'pqrs')
Conclusion
In this Python Tutorial, we learned how to sort a Tuple in Python using sorted() function.