Python Tuple Sort

python-tuple-sort-ipcisco.com-1

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)
numbers=sorted(numbers)
print(numbers)

 

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

 

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

 

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)
numbers=tuple(sorted(numbers))
print(numbers)

 

The output will be a tuple now.

 

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

 

python-tuple-sort-ipcisco.com-1

 

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))
print(numbers)

 

The output of this code will be:

 

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

 

python-tuple-sort-ipcisco.com-2

 

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

 

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

 

 

how-to-sort-python-tuples-ipcisco-1

 

Let’s do the same example as descending alphabetically.

 

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

 

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

 

how-to-sort-python-tuples-ipcisco-2

 

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 *

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k

Python Programming Course

Collapse
Expand