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:

#tuple having structure (name,age,salary)
l=[("Mohan",21,20000),("John",19,10000),("Pankaj",23,25000),("Arpit",20,5000),("Martin",27,7000)]

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.

#tuple having structure (name,age,salary)
l=[("Mohan",21,20000),("John",19,10000),("Pankaj",23,25000),("Arpit",20,5000),("Martin",27,7000)]
sortList=sorted(l, key=lambda x: x[1])
print("Sorted list of tuples based on age:",sortList)

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.

#tuple having structure (name,age,salary)
l=[("Mohan",21,20000),("John",19,10000),("Pankaj",23,25000),("Arpit",20,5000),("Martin",27,7000)]
sortList=sorted(l, key=lambda x: x[1],reverse=True)
print("Sorted list of tuples based on age in descending order:",sortList)

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.

#tuple having structure (name,age,salary)
l=[("Mohan",21,20000),("John",19,10000),("Pankaj",23,25000),("Arpit",20,5000),("Martin",27,7000)]

#Sorting by salary(2nd index of tuple)
sortList=sorted(l, key=lambda x:x[2])
print("Sorted list of tuples based on salary:",sortList)

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.