Sling Academy
Home/Python/How to sort a list of tuples in Python (basic and advanced examples)

How to sort a list of tuples in Python (basic and advanced examples)

Last updated: February 13, 2024

Overview

Sorting is a common operation in programming when you need to organize your data in a particular order. Python, with its rich syntax and powerful data structures, provides simple and efficient ways to sort collections, including lists of tuples. In this tutorial, we’re going to explore various methods to sort a list of tuples in Python, covering both basic and advanced scenarios.

Understanding Tuples

Before diving into sorting, let’s briefly discuss what tuples are. A tuple is an immutable sequence type in Python. It is essentially a collection of items, similar to a list, but with an important distinction – it cannot be modified after its creation. This feature makes tuples a preferred choice for storing a collection of items that should not change.

Basic Sorting

The simplest way to sort a list of tuples is by using the built-in sorted() function. By default, sorted() sorts the list in ascending order based on the first element of each tuple.

my_list = [(2, 'banana'), (1, 'apple'), (3, 'orange')]
sorted_list = sorted(my_list)
print(sorted_list)

This will output:

[(1, 'apple'), (2, 'banana'), (3, 'orange')]

Sorting by Second Element

To sort the list by the second element of each tuple, you can use the key parameter of the sorted() function. The key should be a function that returns the element you want to sort by. The lambda function is particularly useful here.

my_list = [(2, 'banana'), (1, 'apple'), (3, 'orange')]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list)

This will output:

[(1, 'apple'), (2, 'banana'), (3, 'orange')]

Using operator.itemgetter

For more advanced sorting, you can use the itemgetter() function from the operator module. It allows you to specify which item(s) the list should be sorted by more succinctly than a lambda function.

from operator import itemgetter

my_list = [(2, 'banana'), (1, 'apple'), (3, 'orange')]
sorted_list = sorted(my_list, key=itemgetter(1))
print(sorted_list)

This will output the same result as the previous example. Moreover, itemgetter() can be used to sort by multiple criteria.

Sorting by Multiple Criteria

Sometimes, you need to sort your data by more than one criterion. For example, you might want to sort a list of tuples by their second element in ascending order and then by their first element in descending order. To achieve this, you can combine the use of lambda function and the sorted() function’s ability to accept multiple sorting criteria.

my_list = [(2, 'banana'), (1, 'apple'), (3, 'orange'), (3, 'apple')]
sorted_list = sorted(my_list, key=lambda x: (x[1], -x[0]))
print(sorted_list)

This will output:

[(1, 'apple'), (3, 'apple'), (2, 'banana'), (3, 'orange')]

Descending Order

If you want to sort the list in descending order, you can pass reverse=True as an argument to the sorted() function.

my_list = [(2, 'banana'), (1, 'apple'), (3, 'orange')]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)

This will output:

[(3, 'orange'), (2, 'banana'), (1, 'apple')]

In-place Sorting

Python also offers a way to sort lists in-place, using the sort() method. This method modifies the original list and doesn’t return a new list. The sort() method accepts the same parameters as the sorted() function.

my_list = [(2, 'banana'), (1, 'apple'), (3, 'orange')]
my_list.sort()
print(my_list)

This will modify my_list and output the sorted list:

[(1, 'apple'), (2, 'banana'), (3, 'orange')]

Conclusion

In this tutorial, we explored various ways to sort a list of tuples in Python. Whether you’re sorting by one criterion or multiple, in ascending or descending order, Python’s sorted() function and sort() method provide powerful and flexible ways to order your data. With the help of lambda functions and the operator module, you can tailor sorting behavior to suit practically any requirement.

Next Article: Python: How to convert a list to a tuple and vice-versa

Previous Article: How to compare 2 tuples in Python (basic and advanced)

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types