In this Python tutorial, we will learn about the Python sort list of tuples using different examples.
We can sort a list of tuples in Python using the following 7 ways in python.
- Using the sorted() function
- Using the sort() method of a list
- Using the sorted() with key argument
- Using the itemgetter() method
- Using the bubble sort
- Using with the two Elements
- Using the len() function
Python sort list of tuples
In this tutorial, we will discuss how to sort the list of tuples in Python using multiple methods. However, first, we will start with using the sorted() function in Python.
Method-1: Using the sorted() function
The sorted() function is a built-in function in Python that returns a sorted list from any iterable. To sort a list of tuples, we can simply pass the list as the argument to the sorted() function.
By default, the tuples will be sorted based on their first elements, in ascending order.
# Sort a list of tuples by the first element of each tuple
list_of_tuples = [(1, "USA"), (3, "United Kingdom"), (2, "Brazil")]
# Sort the list of tuples by the first element of each tuple
sorted_list = sorted(list_of_tuples)
# Print the sorted list of tuples
print(sorted_list)
The above code prints the sorted list, which is a list of tuples sorted by their first element
Output: [(1, 'USA'), (2, 'Brazil'), (3, 'United Kingdom')]
Read: How to access items of a tuple in Python
Method-2: Using the sort() method of a list
The sort() method sorts the elements of the list in place, meaning that it modifies the original list.
# Create a list of tuples
list_of_tuples = [(1, "USA"), (3, "United Kingdom"), (2, "Brazil")]
# Sort the list of tuples in place by the first element of each tuple
list_of_tuples.sort()
# Print the sorted list of tuples
print(list_of_tuples)
The above code creates a list of tuples, each containing an integer and a string. The list is sorted in place based on the first element of each tuple (the integer), and the sorted list is printed to the console.
Output: [(1, 'USA'), (2, 'Brazil'), (3, 'United Kingdom')]
Read Python concatenate tuples with examples
Method-3: Using the sorted() with key argument
We may want to sort the tuples based on elements other than the first element. To do this, we can use the key argument of the sorted() function. The key argument takes a function that defines how the elements should be sorted.
# Sort the list of tuples based on the second element of the tuples (x[1])
list_of_tuples = [(1, "USA"), (3, "United Kingdom"), (2, "Brazil")]
# Use sorted function with key parameter set to a lambda function
# The lambda function returns the second element of the tuple (x[1])
sorted_list = sorted(list_of_tuples, key=lambda x: x[1])
# Print the sorted list of tuples
print(sorted_list)
The above code defines a list of tuples, where each tuple contains an integer and a string. The sorted function is used to sort the list of tuples, where the sorting key is the string (i.e. x[1]). The sorted list of tuples is then printed.
Output: [(2, 'Brazil'), (1, 'USA'), (3, 'United Kingdom')]
Read Python convert tuple to list
Method-4:Using the itemgetter() method
The itemgetter() function from the operator module is another way to sort a list of tuples in Python. This function returns a callable object that fetches the item at the specified index from an object.
# Import the 'operator' module
from operator import itemgetter
# List of tuples
students = [("James", 20), ("Alex", 19), ("Jonny", 21), ("Messi", 18)]
# Sort the list of tuples by the second element (age) in each tuple
sorted_students = sorted(students, key=itemgetter(1))
print("Sorted list of tuples:", sorted_students)
The above code sorts a list of tuples containing students’ names and their ages in ascending order based on their ages.
Output: Sorted list of tuples: [('Messi', 18), ('Alex', 19), ('James', 20), ('Jonny', 21)]
Read: How to create a list of tuples in Python
Method-5: Using the bubble sort
Bubble sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. It can be used to sort a list of tuples in Python.
# This code implements the bubble sort algorithm to sort a list of tuples based on the second element of each tuple
# Define the bubbleSort function
def bubbleSort(list_of_tuples):
# Determine the number of elements in the list
n = len(list_of_tuples)
# Loop through the elements in the list
for i in range(n):
# Loop through the list from 0 to n - i - 1, comparing each pair of adjacent elements
for j in range(0, n - i - 1):
# If the second element of the current tuple is greater than the second element of the next tuple, swap them
if list_of_tuples[j][1] > list_of_tuples[j + 1][1]:
list_of_tuples[j], list_of_tuples[j + 1] = list_of_tuples[j + 1], list_of_tuples[j]
# Return the sorted list of tuples
return list_of_tuples
# Define the list of tuples
list_of_tuples = [("John", 20), ("Jane", 25), ("Jim", 15)]
# Call the bubbleSort function to sort the list
sorted_list = bubbleSort(list_of_tuples)
# Print the sorted list of tuples
print("Sorted list of tuples:", sorted_list)
The above code defines a function bubbleSort that sorts a list of tuples based on the second element (index 1) of each tuple using the bubble sort algorithm.
- The input list is looped through twice and adjacent elements are swapped if the second element of the first tuple is greater than the second element of the second tuple.
- The sorted list is returned as the output. The code then creates a sample list of tuples and calls the bubbleSort function on it, printing the sorted list as the output.
Output: Sorted list of tuples: [('Jim', 15), ('John', 20), ('Jane', 25)]
Read: Sorting algorithms in Python
Method-6: Using with the two Elements
Sorting a list of tuples based on two elements is also possible in Python. One way to do this is by using the sorted function and a lambda function to specify both the elements to sort by.
# The code sorts a list of tuples based on the first and second elements of each tuple
list_of_tuples = [("John", 20), ("Jane", 25), ("Jim", 15)]
# The sorted function sorts the list_of_tuples based on the lambda function x: (x[0], x[1]).
# This lambda function returns the tuple (x[0], x[1]) as the sorting key.
# The x[0] is the first element of each tuple, which is the name, and x[1] is the second element of each tuple, which is the age.
# The sorting key is based on both the first and second elements of the tuples.
sorted_list = sorted(list_of_tuples, key=lambda x: (x[0], x[1]))
# The sorted list is then printed to the console
print("Sorted list of tuples:", sorted_list)
The above code sorts a list of tuples based on the first element of each tuple, and in the case of a tie (i.e., if two tuples have the same first element), it sorts based on the second element of each tuple.
- The sorted function is used with a lambda function as the key, which specifies the sorting criteria, in this case, sorting first based on the first element and then based on the second element. The sorted list is then printed.
Output: Sorted list of tuples: [('Jane', 25), ('Jim', 15), ('John', 20)]
Method-7: Using the len() function
You can also sort a list of tuples based on the length of one of the elements in the tuple. This is useful if the tuples contain strings and you want to sort them based on the length of the string.
# This code sorts a list of tuples based on the length of the second element (string) in each tuple
# Define a list of tuples, where each tuple contains a name and a greeting
list_of_tuples = [("John", "hello"), ("Jane", "hi"), ("Jim", "hey")]
# Sort the list of tuples based on the length of the second element (greeting string) using the lambda function
sorted_list = sorted(list_of_tuples, key=lambda x: len(x[1]))
# Print the sorted list of tuples
print("Sorted list of tuples:", sorted_list)
The above code sorts a list of tuples by the length of the second element in each tuple.
- The list list_of_tuples contains tuples with two elements, a string, and another string.
- The function sorted is used to sort the list, with the
key
the argument set to lambda x: len(x[1]), which specifies that the sorting should be based on the length of the second element of each tuple.
You may also like to read the following Python tutorials.
- Python concatenate list
- Python Extend Vs Append
- How to Reverse a List in Python
- Python List clear() method [With Examples]
- Python List copy() method [With Examples]
- Python List index() method [With Examples]
In this tutorial, we have discussed how to sort the list of tuples in python. We discussed the Python sort list of tuples with the following methods.
- Python sort list of tuples using the sorted() function
- Python sort list of tuples using the sort() method
- Python sort list of tuples using the sorted() with key argument
- Python sort list of tuples using the itemgetter() method
- Python sort list of tuples using the bubble sort
- Python sort list of tuples using with the two Elements
- Python sort list of tuples using the len() function
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.