Different ways to sort a list of tuples in Python

Jul 06, 2024#python

A list of tuples in Python is a list data structure where each element in the list is a tuple. Tuples are immutable sequences, typically used to store collections of heterogeneous data. Lists, on the other hand, are mutable sequences that can store collections of items, and they can contain any type of item, including other lists and tuples.

list_of_tuples = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]

for number, fruit in list_of_tuples:
    print(f"Number: {number}, Fruit: {fruit}")

# Output:
# Number: 1, Fruit: apple
# Number: 2, Fruit: banana
# Number: 3, Fruit: cherry

Remember that each tuple within the list can have a different number of elements:

list_of_tuples = [
    (1, 'apple'),
    (2, 'banana', 3.5),
    (3, 'cherry', 'red', 5.0),
    (4, )
]

for item in list_of_tuples:
    print(item)

# Output:
# (1, 'apple')
# (2, 'banana', 3.5)
# (3, 'cherry', 'red', 5.0)
# (4,)

When sorting a list of tuples that contains elements of different data types at the specific comparing position, Python will raise a TypeError because it cannot compare incompatible types directly.

list_of_tuples = [
    (1, 'apple'),
    (2, 3),
    (3, 'banana'),
    (4, 2)
]

try:
    sorted_list = sorted(list_of_tuples, key=lambda x: x[1])
except TypeError as e:
    print(e)

# Output:
# '<' not supported between instances of 'int' and 'str'

If you have a list of tuples with mixed data types in the sorting position, you need to handle these differences explicitly to avoid errors.

In this tutorial of different ways to sort a list of tuples, the assumption was that the tuples contain elements of comparable types (e.g., all integers, all strings) in the positions being used for sorting. This ensures that sorting operations can be performed without encountering type errors.

In Python, both sorted() and list.sort() are used to sort lists:

# Returns a new sorted list.
sorted(iterable, key=None, reverse=False)

# Modifies the original list in place.
list.sort(key=None, reverse=False)
  1. Sorting by the first element
list_of_tuples = [(2, 3), (1, 2), (4, 1), (3, 4)]
sorted_list = sorted(list_of_tuples)
print(sorted_list)  # Output: [(1, 2), (2, 3), (3, 4), (4, 1)]

or sort in reverse order:

list_of_tuples = [(2, 3), (1, 2), (4, 1), (3, 4)]
sorted_list = sorted(list_of_tuples, reverse=True)
print(sorted_list)  # Output: [(4, 1), (3, 4), (2, 3), (1, 2)]
  1. Sorting by a specific element (e.g. second element)
list_of_tuples = [(2, 3), (1, 2), (4, 1), (3, 4)]
sorted_list = sorted(list_of_tuples, key=lambda x: x[1])
print(sorted_list)  # Output: [(4, 1), (1, 2), (2, 3), (3, 4)]
  1. Sorting by multiple elements
list_of_tuples = [(2, 3), (1, 2), (4, 1), (3, 4), (2, 2)]
sorted_list = sorted(list_of_tuples, key=lambda x: (x[1], x[0]))
print(sorted_list)  # Output: [(4, 1), (1, 2), (2, 2), (2, 3), (3, 4)]
  1. Sorting by using custom sorting function for more complex sorting logic
def custom_sort(tuple):
    return tuple[1] - tuple[0]

list_of_tuples = [(2, 3), (1, 2), (4, 1), (3, 4)]
sorted_list = sorted(list_of_tuples, key=custom_sort)
print(sorted_list)  # Output: [(4, 1), (2, 3), (1, 2), (3, 4)]
  1. Sorting by using operator.itemgetter
from operator import itemgetter

list_of_tuples = [(2, 3), (1, 2), (4, 1), (3, 4)]
sorted_list = sorted(list_of_tuples, key=itemgetter(1))
print(sorted_list)  # Output: [(4, 1), (1, 2), (2, 3), (3, 4)]