Sorting is very important function and lesson of Python Programming Course. In this python tuple sort lesson, we will focus on tuple sorting and we will learn how to sort tuples in python. A python tuple is an immutable ordered requence. The order of the tuple items can not be changed by default. But there is a trick for this. We can use sorted function To sort a tuple. When we use this function, the tuple is converted to a list as sorted. After that we can convert this list to a tuple again.
We will give different sorting examples to learn sorting in python. Here, we will use sort method to sort the items in a python tuple.
In the first example, we will try to sort a number tuple. Here, we will see that, with this sorted function, the tuple will be converted to a list and then sorted.
The output of this python tuple sort example will be like below:
You can also check Python Tuple Methods
You can also watch the video of this lesson!
We need a sorted tuple not a sorted list. So, we should convert this list to tuple for our purpose.
The output will be a tuple now.
This is ascending sort. The numbers are sorted from the lower one to the higher one. Npw, let’s do this sorting descending. Here, we will use reverse parameter and set it as True.
The output of this code will be:
Now, let’s do a string tuple example. Here, the default sorting will be ascending alphabetically.
Let’s do the same example as descending alphabetically.
As you can see above, the tuple sorted firstly by converting a list. And then we have convert the sorted list to tuple with tuple method.
In this lesson, we have learned how to do python tuple sorting. We have given different examples for python tuple sort. Do not forget, by default tuples can not be changed, they are immutable. But here we are doing a python trick to sort a tuple.