Python sort list of tuples by 1st and 2nd elements [with Examples]
Table of Contents
Table of Contents
What is a list of tuples ?
A list of tuples is a collection of ordered elements, where each element is a tuple.
A tuple is an immutable sequence of values, separated by commas and enclosed in parentheses. Tuples can contain elements of different types, and they can be indexed and sliced like lists. However, unlike lists, tuples cannot be modified once they are created.
A list of tuples is created by enclosing a sequence of tuples in square brackets, separated by commas.
For Example –
Here’s the list of tuples of a person with the name and age.
persons = [("Robert" ,21) ,("Mark" ,50) ,("John", 35)]
print(persons)
Output:
[(Robert, 21), ('Mark', 50), ('John', 35)]
Types of tuple Sorting
Sort list of tuples using sort()
The sort() method is the inbuilt method in python which takes an optional argument called key.
The key argument is a function that takes a single argument (in this case, a tuple) and returns a value that will be used for sorting.
syntax:
list_name.sort(key)
For example –
Here is a list of students with their grades in maths and physics.
First we will sort the list using the maths grades.
def get_math_grade(student):
return student[1]students.sort(key = get_math_grad
students = [('Alice', 85, 90), ('Bob', 92, 45), ('Charlie', 78 ,56), ('David', 90 ,34)]
print(students)
Output –
[('Charlie', 78, 56), ('Alice', 85, 90), ('David', 90, 34), ('Bob', 92, 45)]
This code defines a function get_math_grade() that takes a tuple representing a student and returns their maths grade (the second element of the tuple).
It then calls the sort() method on the students list, passing get_grade as the key argument.
Now we will sort them using physics grades
def get_physics_grade(student):
return student[2]students.sort(key = get_physics_grade)
students = [('Alice', 85, 90), ('Bob', 92, 45), ('Charlie', 78 ,56), ('David', 90 ,34)]
print(students)
Output:
[('David', 90, 34), ('Bob', 92, 45), ('Charlie', 78, 56), ('Alice', 85, 90)]
Using Sorted() Function
sorted function is similar to sort() method in the matter of functionality. It also takes the key argument which is a function that takes a single argument (in this case, a tuple) .
The only difference is that the sorted() function returns a new sorted list, leaving the original list unchanged.
If you want to modify the original list in place, you can use the sort() method of the list object instead .
Syntax –
new_list = sorted(old_list , key)
For example –
Imagine there is a tuple of products like (name , price ,stock) and we want to sort this list of tuples using price and stock.
def get_price(fruit):
return fruit[1]
def get_stock(fruit):
return fruit[2]
fruits = [('Mango', 85, 90), ('PineApple', 92, 45), ('Kiwi', 78 ,56), ('Oranges', 90 ,34)]
price_sorted = sorted(fruits ,key = get_price)
stock_sorted = sorted(fruits , key = get_stock)
print("Using price sorting :" , price_sorted)
print("Using stock sorting :" , stock_sorted)
Output –
Using price sorting : [('Kiwi', 78, 56), ('Mango', 85, 90), ('Oranges', 90, 34), ('PineApple', 92, 45)]
Using stock sorting : [('Oranges', 90, 34), ('PineApple', 92, 45), ('Kiwi', 78, 56), ('Mango', 85, 90)]
In the above example we created 2 key functions to return the price as [1] index and stock as [2] index. by using these key functions we sorted the fruits list and created 2 new lists to store the result of the sorting.
Errors while sorting list of tuples
Syntax Error
Declaring the tuple needs round parentheses and declaring list requires square parentheses; using the wrong bracket or not closing the inner bracket can cause the syntax error which can lead to program failure.
For Example –
fruits = [['Mango', 85, 90], ['PineApple', 92, 45], ['Kiwi', 78 ,56], ['Oranges', 90 ,34]]
The above code will create a nested list instead of list of tuples
Note : the code will still work
Index Error
These types of errors are caused when we try to modify the values of tuples using index values .
This causes errors because tuples are immutable by default.
fruits = [('Mango', 85, 90), ('PineApple', 92, 45), ('Kiwi', 78 ,56), ('Oranges', 90 ,34)]
fruits[0][1] = 56
Output –
TypeError: 'tuple' object does not support item assignment
Type Error
This error occurs when the elements inside the tuples cannot be compared using the ‘<‘ operator. For example, if one of the tuples contains a string and another contains an integer, the sorting algorithm may not know how to order them.
For Example –
def get_out(person):
return person[1]
persons = [("Alice",60), ("Tom",70), ("Alex","60"), ("Steve",50)]
persons.sort(key = get_out)print(persons)
Output –
File "/home/main.py", line 6, in <module>
persons.sort(key = get_out)TypeError: '<' not supported between instances of 'str' and 'int'
Python sort list of Tuples – Use Cases
Ranking Systems
When you have a list of items that you want to rank based on some criteria, sorting a list of tuples can be a great way to do it.
For example, if you have a list of movies and you want to rank them based on their ticket price or customer rating, you can create a list of tuples with each tuple containing the movie name and its corresponding ticket price or rating. Then you can sort the list based on the ticket price or rating.
def sortByPrice(movie):
return movie[1]
def sortByRating(movie):
return movie[2]
movies = [("Avatar",1000,5.7),("Top Gun",300 ,8.6),("007 James Bond",100,9.4),("Angry Birds",1500,8.5)]
movies.sort( key = sortByPrice)
print("Sorted by Price :",movies)
movies.sort( key = sortByRating)
print("Sorted by Rating :",movies)
Output –
Sorted by price : [('007 James Bond', 100, 9.4), ('Top Gun', 300, 8.6), ('Avatar', 1000, 5.7), ('Angry Birds', 1500, 8.5)]
Sorted by Rating : [('Avatar', 1000, 5.7), ('Angry Birds', 1500, 8.5), ('Top Gun', 300, 8.6), ('007 James Bond', 100, 9.4)]
Data Analysis
When you have a large dataset and you want to analyse it, sorting the data based on certain criteria can be a good way to identify patterns and trends.
For Example –
You want to sort the students by their total marks in the final exam.Create a list of tuples with the name of the student and all the marks inside the tuple.
def sortByTotal(student):
return student[1]+student[2]students.sort( key = sortByTotal)
students = [("Alice",10,57),("Alex",80 ,86),("Steve",60,20),("Lizel",45,85)]
print("Sorted by price :",students)
Output:
Sorted by price : [('Alice', 10, 57), ('Steve', 60, 20), ('Lizel', 45, 85), ('Alex', 80, 86)]