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:
1 2 3 4 |
#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.
1 2 3 4 5 6 |
#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.
1 2 3 4 5 6 |
#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.
1 2 3 4 5 6 7 8 |
#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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.