How do you sort a list of tuples in Python by both elements?

How to Sort a List of Tuples with the Sorted Function

Let’s take the following list of tuples:

numbers = [(2,5,3), (3,1,2), (0,0,1)]

I want to sort the tuples in the list based on the first item in each tuple.

Python provides a function called sorted() that can be used to sort items in iterables.

Considering that a list is an iterable I would expect the sorted() function to be able to sort our list of tuples.

Let’s find out:

>>> print(sorted(numbers)) [(0, 0, 1), (2, 5, 3), (3, 1, 2)]

As you can see the order of the tuples in the list has changed.

By default the sorted() function sorts the tuples based on the first item in each tuple. That’s why the first tuple in the sorted list starts with 0, the second with 2 and the third with 3.

I wonder what happens if the first element of each tuple is the same:

>>> numbers = [(2,5,3), (2,1,2), (2,0,1)] >>> print(sorted(numbers)) [(2, 0, 1), (2, 1, 2), (2, 5, 3)]

The next sorting criteria used by the sorted() function is the second element of each tuple.

And if all the tuples have the same second element?

>>> numbers = [(2,5,3), (2,5,2), (2,5,1)] >>> print(sorted(numbers)) [(2, 5, 1), (2, 5, 2), (2, 5, 3)]

This time the tuples in the list are sorted based on the third element once they have been sorted based on the first and the second elements in each tuple that in this case are the same.

Python program to sort a list of tuples by second Item

Given a list of tuples, write a Python program to sort the tuples by the second item of each tuple.

Examples:

Input : [('for', 24), ('Geeks', 8), ('Geeks', 30)] Output : [('Geeks', 8), ('for', 24), ('Geeks', 30)] Input : [('452', 10), ('256', 5), ('100', 20), ('135', 15)] Output : [('256', 5), ('452', 10), ('135', 15), ('100', 20)]


Method #1: Using the Bubble Sort

Using the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the second element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).




# Python program to sort a list of tuples by the second Item
# Function to sort the list of tuples by its second item
def Sort_Tuple(tup):
# getting length of list of tuples
lst = len(tup)
for i in range(0, lst):
for j in range(0, lst-i-1):
if (tup[j][1] > tup[j + 1][1]):
temp = tup[j]
tup[j]= tup[j + 1]
tup[j + 1]= temp
return tup
# Driver Code
tup =[('for', 24), ('is', 10), ('Geeks', 28),
('Geeksforgeeks', 5), ('portal', 20), ('a', 15)]
print(Sort_Tuple(tup))

Output:



[('Geeksforgeeks', 5), ('is', 10), ('a', 15), ('portal', 20), ('for', 24), ('Geeks', 28)]

Method #2: Using sort() method

While sorting via this method the actual content of the tuple is changed, and just like the previous method, the in-place method of the sort is performed.




# Python program to sort a list of
# tuples by the second Item using sort()
# Function to sort hte list by second item of tuple
def Sort_Tuple(tup):
# reverse = None (Sorts in Ascending order)
# key is set to sort using second element of
# sublist lambda has been used
tup.sort(key = lambda x: x[1])
return tup
# Driver Code
tup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)]
# printing the sorted list of tuples
print(Sort_Tuple(tup))

Output:

[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]


Method #3: Using sorted() method

Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three:

Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Key(optional) : A function that would serve as a key or a basis of sort comparison.
Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.




# Python program to sort a list of
# tuples by the second Item using sorted()
# Function to sort the list by second item of tuple
def Sort_Tuple(tup):
# reverse = None (Sorts in Ascending order)
# key is set to sort using second element of
# sublist lambda has been used
return(sorted(tup, key = lambda x: x[1]))
# Driver Code
tup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)]
# printing the sorted list of tuples
print(Sort_Tuple(tup))

Output:

[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]

How do you sort a list of tuples in Python by both elements?




Article Tags :
Python
Python Programs
School Programming
Python list-programs
Python tuple-programs
python-list
python-tuple
Practice Tags :
python-list

Introduction

Sorting algorithms are an essential part of every programming language, as they allow us to organize data efficiently. Python has its sorting methods, the built-in function sorted(...) and the built-in method list.sort(...). They allow us to sort various data types, such as a list of tuples.

In this article, we will explore lists, tuples, lambda functions, and sorting. We will then use our understanding of these concepts to sort a list of tuples in Python.

Sort List of Tuples in Python

Consider that you have a list of tuples. You can sort the tuples in the list like you sort a list of integers.

Based on the fact that a tuple can contain multiple elements in it, you can sort this list of tuples based on some ith element of all the tuples.

In this tutorial, we will learn how to sort a list of tuples based on the first, second, or ith element in the tuples. There are many ways to do so. We shall look into examples for the following ways.

  • Use inbuilt list.sort() method.
  • Use bubble sort()

You can use any sorting() algorithm. The process should be same as that of using bubble sort given in this tutorial.

Example 1: Sort List of Tuples using list.sort()

In this example, we take tuples containing name and marks of students in a class. We shall sort these tuples based on the marks, the second element in all the tuples.

Python Program

list_students = [('Saranya',84), ('Surya',92) , ('Joy',88) , ('Sree',86), ('Ritha',89)] #sort by second element of tuple list_students.sort(key = lambda x: x[1]) #index 1 means second element print(list_students)Run

Output

[('Saranya', 84), ('Sree', 86), ('Joy', 88), ('Ritha', 89), ('Surya', 92)]

The list of tuples is ordered in the increasing order of the second element in the tuples. You may change the order from increasing to decreasing by passing True for reverse parameter of sort() method. Or you can also use list.reverse() on the ascending ordered list.

In the following example, we will sort the list of tuple in the descending order, using reverse parameter.

Python Program

list_students = [('Saranya',84), ('Surya',92) , ('Joy',88) , ('Sree',86), ('Ritha',89)] #sort by second element of tuple list_students.sort(key = lambda x: x[1], reverse=True) print(list_students)Run

Output

[('Surya', 92), ('Ritha', 89), ('Joy', 88), ('Sree', 86), ('Saranya', 84)]

Example 2: Sort List of Tuples using Bubble Sort Algorithm

We shall take the same list of tuples in the above example and sort them based on the marks as before, but using bubble sort algorithm.

Python Program

list_ = [('Saranya',84), ('Surya',92) , ('Joy',88) , ('Sree',86), ('Ritha',89)] #sort by second element of tuple ith = 1 list_length = len(list_) for i in range(0, list_length): for j in range(0, list_length-i-1): if (list_[j][ith] > list_[j + 1][ith]): temp = list_[j] list_[j]= list_[j + 1] list_[j + 1]= temp print(list_)Run

Output

[('Saranya', 84), ('Sree', 86), ('Joy', 88), ('Ritha', 89), ('Surya', 92)]

In the above program, ith variable defines the position in tuples, by which sorting has to be done. Let us now sort the list of tuples by the first element in the tuples.

Python Program

list_ = [('Saranya',84), ('Surya',92) , ('Joy',88) , ('Sree',86), ('Ritha',89)] #sort by second element of tuple ith = 0 list_length = len(list_) for i in range(0, list_length): for j in range(0, list_length-i-1): if (list_[j][ith] > list_[j + 1][ith]): temp = list_[j] list_[j]= list_[j + 1] list_[j + 1]= temp print(list_)Run

Output

[('Joy', 88), ('Ritha', 89), ('Saranya', 84), ('Sree', 86), ('Surya', 92)]

Summary

In this tutorial of Python Examples, we learned how to sort a list of tuples using inbuilt functions and sorting algorithms, with the help of well detailed examples.

  • Python Tuple vs List
  • Python List of Tuples