Python sort list of tuples

In this tutorial, we will see about how to sort list of tuples on the basis of various criterion.

Let’s understand with the help of example
Let’s say you have list of tuples as below:

Now you want to sort list of tuples based on age and age is 1st index in tuple.
You can use below code to sort list of tuples based on age.

Output:

Sorted list of tuples based on age: [(‘John’, 19, 10000), (‘Arpit’, 20, 5000), (‘Mohan’, 21, 20000), (‘Pankaj’, 23, 25000), (‘Martin’, 27, 7000)]

If you want to sort in descending order, then you just need to add reversed=true as below.

Output:

Sorted list of tuples based on age: [(‘Martin’, 27, 7000), (‘Pankaj’, 23, 25000), (‘Mohan’, 21, 20000), (‘Arpit’, 20, 5000), (‘John’, 19, 10000)]

Let’s sort list of tuple on the basis of salary now.

Output:

Sorted list of tuples based on age in descending order: [(‘Arpit’, 20, 5000), (‘Martin’, 27, 7000), (‘John’, 19, 10000), (‘Mohan’, 21, 20000), (‘Pankaj’, 23, 25000)]

That’s all about sorting list of tuples.

Was this post helpful?

Leave a Reply

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