How to Sort a List of Tuples in Python

by | Programming, Python, Tips

In Python, you can sort a list of tuples by the elements of each tuple. This tutorial will go through how to sort a list of tuples with code examples.


Using the sort() Method

The method sort() is a built-in method for the list data type. The syntax of the sort method is

list.sort(reverse, key)

Parameters:

  • reverse: Optional. If reverse=True sort the list in descending order. If reverse = False sort the list in ascending order. The default value is False.
  • key: Optiona. A function to specify the sorting criteria.

We can use the sort() method to sort a list of tuples by the first or second element. Let’s look at an example of each.

Sorting List of Tuples by First Element using sort()

In the following code, we will define a function that takes a list of tuples as an argument. The function calls the sort() method using a lambda function as the key function.

The index value of [0] tells the sort() method to sort by the first element. The function then returns the sorted list of tuples.

With the function defined, we can create a list of tuples to sort, pass it to the function and print the result to the console.

def sort_tup_first_ele(tup):

    tup.sort(key = lambda x: x[0])

    return tup

tup = [('margherita', 10), ('pepperoni', 3), ('hawaiian', 5), ('four cheeses', 8), ('marinara', 6)]

print(sort_tup_first_ele(tup))

Let’s run the code to get the result:

[('four cheeses', 8), ('hawaiian', 5), ('margherita', 10), ('marinara', 6), ('pepperoni', 3)]

Sorting List of Tuples by Second Element using sort()

To sort by the second element, we need to change the index value in the lambda function from 0 to 1 as shown below:

def sort_tup_second_ele(tup):

    tup.sort(key = lambda x: x[1])

    return tup

tup = [('margherita', 10), ('pepperoni', 3), ('hawaiian', 5), ('four cheeses', 8), ('marinara', 6)]

print(sort_tup_second_ele(tup))

Let’s run the code to get the result:

[('pepperoni', 3), ('hawaiian', 5), ('marinara', 6), ('four cheeses', 8), ('margherita', 10)]

Using the sorted() Method

The sorted() method returns a list of values from the specified iterable object, which can be a list, set, string, or tuple. The syntax of the sorted() method is:

sorted(iterable, key, reverse)

Parameters:

  • iterable: Required. The iterable object to arrange in ascending or descending order.
  • key: Optional. Function that serves as the key for the sort comparison.
  • reverse: Optional. If reverse=True sort in descending order. If reverse=False, sort in ascending order. Default is reverse=False.

The sorted() method differs from the sort() method in that it is not exclusive to the list data type, and you can pass any iterable object to it. Also, sort() sorts the list in place, whereas sorted() returns a new list object with the sorted values.

We can use the sorted() method to sort a list of tuples by the first or second element. Let’s look at an example of each.

Sorting List of Tuples by First Element using sorted()

In the following code, we will define a function that takes a list of tuples as an argument. The function calls the sorted() method using a lambda function as the key function and the list of tuples as the iterable to sort.

The index value of [0] tells the sorted() method to sort by the first element. The function then returns the sorted list of tuples. With the function defined, we can create a list of tuples to sort, pass it to the function and print the result to the console.

def sort_tup_first_ele(tup):

    return(sorted(tup, key = lambda x: x[0]))

tup = [('margherita', 10), ('pepperoni', 3), ('hawaiian', 5), ('four cheeses', 8), ('marinara', 6)]

print(sort_tup_first_ele(tup))
[('four cheeses', 8), ('hawaiian', 5), ('margherita', 10), ('marinara', 6), ('pepperoni', 3)]

Sorting List of Tuples by Second Element using sorted()

To sort by the second element, we need to change the index value in the lambda function from 0 to 1 as shown below:

def sort_tup_second_ele(tup):

    return(sorted(tup, key = lambda x: x[1]))

tup = [('margherita', 10), ('pepperoni', 3), ('hawaiian', 5), ('four cheeses', 8), ('marinara', 6)]

print(sort_tup_second_ele(tup))
[('pepperoni', 3), ('hawaiian', 5), ('marinara', 6), ('four cheeses', 8), ('margherita', 10)]

Using the Bubble Sort Method

Bubble sort is a simple sorting algorithm that compares pairs of adjacent elements. If the elements are not in order, the algorithm swaps them around. The bubble sort algorithm is not suitable for large datasets because it has a complexity of O(n$latex ^{2}$) when n is the number of items. We can use the bubble sort algorithm to sort by the first or second element in a tuple.

Sorting List of Tuples by First Element using Bubble Sort

The following code defines a function that takes a list of tuples, tup, and an index value, idx, as arguments. The function assigns the length of the list to a variable called lst. The function uses two for loops to get the adjacent tuples in the list.

Within the second for loop, we have an if statement to check if the element with index idx in the first tuple is greater than the element with index idx in the second tuple. In that case, we switch the tuple order. Once we have checked all adjacent pairs, the function returns the sorted list of tuples.

def bubble_sort_tup(tup, idx):

    lst = len(tup)

    for i in range(0, lst):

        for j in range(0, lst-i-1):
            
            # compare adjacent elements
            
            if (tup[j][idx] ≻ tup[j + 1][idx]):

                # swap them

                temp = tup[j]

                tup[j] = tup[j + 1]

                tup[j + 1] = temp

    return tup

tup = [('margherita', 10), ('pepperoni', 3), ('hawaiian', 5), ('four cheeses', 8), ('marinara', 6)]

print(bubble_sort_tup(tup, 0))         

To sort by the first element, we need to pass the index value of 0 to the bubble_sort_tup function. Let’s run the code to get the output:

[('four cheeses', 8), ('hawaiian', 5), ('margherita', 10), ('marinara', 6), ('pepperoni', 3)]

Sorting List of Tuples by Second Element using Bubble Sort

To sort by the second element, we need to pass the index value of 1 to the bubble_sort_tup function. Let’s run the code to get the output:

tup = [('margherita', 10), ('pepperoni', 3), ('hawaiian', 5), ('four cheeses', 8), ('marinara', 6)]

print(bubble_sort_tup(tup, 1))   
[('pepperoni', 3), ('hawaiian', 5), ('marinara', 6), ('four cheeses', 8), ('margherita', 10)]

Using Bubble Sort In Descending Order

If we want to use the Bubble sort algorithm in descending order, we must change the if statement in the second for loop. Instead of checking if the element in the first tuple is greater than that in the second tuple, we check for less than. Let’s look at the revised function:

def bubble_sort_tup(tup, idx):

    lst = len(tup)

    for i in range(0, lst):

        for j in range(0, lst-i-1):

            # compare adjacent elements 

            if (tup[j][idx] ≺ tup[j + 1][idx]):

            # swap them

                temp = tup[j]

                tup[j] = tup[j + 1]

                tup[j + 1] = temp

    return tup

Let’s run the code with the reversed sorting in place:

tup = [('margherita', 10), ('pepperoni', 3), ('hawaiian', 5), ('four cheeses', 8), ('marinara', 6)]
print(bubble_sort_tup(tup, 0))
[('pepperoni', 3), ('marinara', 6), ('margherita', 10), ('hawaiian', 5), ('four cheeses', 8)]

Summary

Congratulations on reading to the end of this tutorial. You can sort a list of tuples using the sort() method, the sorted() method, or the bubble sort algorithm. You can sort by a specific element by passing the index value to the lambda function when calling the sort() or sorted() method. For the bubble sort algorithm, you can specify the index value in the if statement for comparing the elements.

For further reading on the lists and tuples, go to the article: What is the Difference Between List and Tuple in Python?

For further reading on sorting algorithms, go to the article: How to do Bubble Sort in Python.

For further reading on list manipulation, go to the article: How to Get Unique Values from List in Python.
Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨