Python Tuple Sort

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.


numbers = (10, 33, 7, 80, 55, 2)


The output of this python tuple sort example will be like below:


[2, 7, 10, 33, 55, 80]


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.


numbers = (10, 33, 7, 80, 55, 2)


The output will be a tuple now.


(2, 7, 10, 33, 55, 80)


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.


numbers = (10, 33, 7, 80, 55, 2)
numbers=tuple(sorted(numbers, reverse=True))


The output of this code will be:


(80, 55, 33, 10, 7, 2)


Now, let’s do a string tuple example. Here, the default sorting will be ascending alphabetically.


animals = ("cat", "lion", "eagle", "bear", "horse")
('bear', 'cat', 'eagle', 'horse', 'lion')





Let’s do the same example as descending alphabetically.


animals = ("cat", "lion", "eagle", "bear", "horse")
animals=tuple(sorted(animals, reverse=True))


('lion', 'horse', 'eagle', 'cat', 'bear')




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.


Back to: Python Programming Course > Python Tuples

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course