Sorting List of Tuples using Key and Lambda Function in Python
- Posted by Admin
- on August 23, 2022
- in Python
- No Comments.
				 Post Views: 1,345
			
Here we will be sorting a list of tuples having first names and last names of cricket players by their last names.
This is the list of tuples:
players = [("Sachin", "Tendulkar"),
               ("Sunil","Gavaskar"),
               ("Kapil","Dev"),       
               ("MS","Dhoni"),
               ("Saurav","Ganguly")]The desired output is should be like
[(‘Kapil’, ‘Dev’), (‘MS’, ‘Dhoni’), (‘Saurav’, ‘Ganguly’), (‘Sunil’, ‘Gavaskar’), (‘Sachin’, ‘Tendulkar’)]
Solution
# Input List of Tuples 
players = [("Sachin", "Tendulkar"),
               ("Sunil","Gavaskar"),
               ("Kapil","Dev"),       
               ("MS","Dhoni"),
               ("Saurav","Ganguly")]
# Using Lambda Function sorting can be applied to the last name
players.sort(key=lambda x: x[1])
# Print after sorting
print(players)
# Output 
# [('Kapil', 'Dev'), ('MS', 'Dhoni'), ('Saurav', 'Ganguly'), ('Sunil', 'Gavaskar'), ('Sachin', 'Tendulkar')]If we have two players with the same last name and want the first name also to be sorted after the last name, then the below solution works for you.
Use of a custom key using the lambda function, we can achieve this.
# Input List of Tuples 
players = [("Sachin", "Tendulkar"),
           ("Ramesh", "Tendulkar"),
               ("Sunil","Gavaskar"),
               ("Kapil","Dev"),       
               ("MS","Dhoni"),
               ("Saurav","Ganguly")]
# Custom Key 
custom_key = lambda x: (x[1], x[0]) 
# Using Lambda Function sorting can be applied to the last name
print(sorted(players, key=custom_key))
# Output 
# [('Kapil', 'Dev'), ('MS', 'Dhoni'), ('Saurav', 'Ganguly'), 
# ('Sunil', 'Gavaskar'), ('Ramesh', 'Tendulkar'), ('Sachin', 'Tendulkar')]