Python sort list of tuples

Previous
Next

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.

#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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog