Python Sort A List Of Tuples

7 min read

Python sort a list of tuples is a common task when working with records such as names and scores, product IDs and prices, or dates and values. Python provides simple tools for ordering tuples by one field, several fields, or a custom rule while keeping the code readable and efficient Worth keeping that in mind. Simple as that..

Introduction

A tuple is an ordered, immutable collection, so a list of tuples is often used to represent structured data:

students = [
    ("Alice", 88),
    ("Bob", 95),
    ("Charlie", 72),
]

Each tuple contains related values. In this example, index 0 stores the student’s name and index 1 stores the score. Sorting the list changes the order of the tuples without changing the values inside them.

Python supports two primary methods:

  • sorted() creates and returns a new sorted list.
  • list.sort() rearranges the existing list in place.

Both accept a key function and a reverse argument, making them suitable for most tuple-sorting tasks That alone is useful..

Sort a List of Tuples by One Element

Use the key parameter to tell Python which tuple element should control the ordering. A lambda function is a convenient way to select that element.

students = [
    ("Alice", 88),
    ("Bob", 95),
    ("Charlie", 72),
]

sorted_students = sorted(students, key=lambda student: student[1])
print(sorted_students)

Output:

[('Charlie', 72), ('Alice', 88), ('Bob', 95)]

The expression student[1] selects the score from each tuple. Python sorts the tuples according to those scores, from lowest to highest by default.

To sort in descending order, add reverse=True:

top_students = sorted(students, key=lambda student: student[1], reverse=True)
print(top_students)

This places the highest score first.

Use list.sort() to Sort in Place

If there is no need to preserve the original order, call the list’s sort() method:

students = [
    ("Alice", 88),
    ("Bob", 95),
    ("Charlie", 72),
]

students.sort(key=lambda student: student[1])
print(students)

The important difference is that students.sort() modifies the original list and returns None. Which means, this is incorrect:

# Incorrect: sorted_result will be None
sorted_result = students.sort(key=lambda student: student[1])

Use this instead:

students.sort(key=lambda student: student[1])

Choose sorted() when the original ordering matters, such as when the same data must be displayed in several different orders. Day to day, choose list. sort() when memory use matters or the original order is no longer needed.

Sort by the First Element

Tuples are compared element by element by default, so a list containing comparable values at index 0 can be sorted without an explicit key:

people = [
    ("Charlie", 30),
    ("Alice", 25),
    ("Bob", 35),
]

people.sort()
print(people)

Output:

[('Alice', 25), ('Bob', 35), ('Charlie', 30)]

For clarity, the key can still be written explicitly:

people.sort(key=lambda person: person[0])

An explicit key is especially useful when the default comparison would otherwise use additional tuple elements as tie-breakers Still holds up..

Sort by Multiple Elements

To sort by more than one field, return a tuple from the key function:

employees = [
    ("Alice", "Engineering", 75000),
    ("Bob", "Sales", 62000),
    ("Charlie", "Engineering", 80000),
    ("Diana", "Sales", 70000),
]

employees.sort(key=lambda employee: (employee[1], employee[2]))
print(employees)

This sorts employees first by department and then by salary within each department. Python compares the first key values. When two values are equal, it compares the second values. If those are also equal, it continues through the remaining key fields Nothing fancy..

The same result can be written with operator.itemgetter():

from operator import itemgetter

employees.sort(key=itemgetter(1, 2))

itemgetter(1, 2) is often faster and more readable for simple field selection. It also works with mappings, allowing a list of dictionaries to be sorted by named fields Small thing, real impact..

Use Mixed Ascending and Descending Order

Setting reverse=True reverses the entire result, so it cannot independently control each sorting field. For numeric values, negating a field is a concise solution:

scores = [
    ("Alice", 95, 12),
    ("Bob", 95, 8),
    ("Charlie", 90, 20),
]

scores.sort(key=lambda item: (-item[1], item[2]))

This sorts by score from highest to lowest while sorting attempt numbers from lowest to highest. The negative sign reverses only the numeric score field.

For text or non-numeric values, Python’s stable sorting behavior can be used. A stable sort preserves the relative order of records with equal keys. Sort by the lower-priority field first, and then by the higher-priority field:

records = [
    ("Alice", "B", 90),
    ("Bob", "A", 85),

```python
# Suppose we need to order the records so that the department appears in reverse
# alphabetical order while the score is kept in normal ascending order

To handle a case where one field must be sorted in reverse order while another retains its natural order, you can exploit Python’s stable sorting algorithm. On top of that, the idea is to perform two separate sorts: first sort by the lower‑priority field (the one that should stay in its default direction), then sort by the higher‑priority field, applying the desired direction only to that field. Because the sort is stable, the ordering established by the first pass is preserved wherever the keys of the second pass compare equal.

### Example: reverse department, ascending score

```python
records = [
    ("Alice", "B", 90),
    ("Bob",   "A", 85),
    ("Carol", "C", 92),
    ("Dave",  "B", 88),
    ("Eve",   "A", 95),
]

# 1️⃣  Sort by the lower‑priority field: score (ascending)
records.sort(key=lambda r: r[2])          # → score ascending

# 2️⃣  Sort by the higher‑priority field: department (descending)
#     Using reverse=True flips the entire order, but because the
#     previous sort is stable, scores stay ordered within each
#     department group.
records.sort(key=lambda r: r[1], reverse=True)

print(records)

Output

[('Eve', 'A', 95),
 ('Bob',  'A', 85),
 ('Dave', 'B', 88),
 ('Alice','B', 90),
 ('Carol','C', 92)]

Explanation:

  1. After the first sort, the list is ordered by score: 85, 88, 90, 92, 95.
  2. The second sort groups the items by department in reverse alphabetical order (C, B, A).
    Because the sort is stable, the relative order of items that share the same department (their scores) remains exactly as it was after the first pass—hence the scores stay ascending inside each department block.

Alternative: a single‑pass key with a custom transformer

If you prefer a one‑liner and the field you need to reverse is numeric, you can negate it as shown earlier. For non‑numeric fields you can map them to values that invert the natural order, such as using the negative of their Unicode code points or a lookup table that assigns opposite ranks. For strings, a simple trick is to sort by the negative of the ordinal values of each character:

def rev_str(s):
    # Return a tuple of negative code points; Python compares tuples lexicographically.
    return tuple(-ord(ch) for ch in s)

records.sort(key=lambda r: (rev_str(r[1]), r[2]))

This yields the same result as the two‑step stable sort but may be less readable; the stable‑sort approach is usually clearer and just as efficient for modest‑size data.

When to choose which technique

Situation Recommended approach
Only numeric fields need reversal Negate the field in a single key tuple
One or more non‑numeric fields reverse Stable sort: low‑priority first, then high‑priority with reverse=True
Complex custom ordering (e.On top of that, g. , locale) Build a key function that returns a comparable object (tuple, custom class)
Very large lists where speed matters Use `operator.

By combining Python’s guarantee of sort stability with simple key transformations, you can achieve any mixture of ascending and descending orders without resorting to external libraries or complicated comparison functions Worth knowing..


Conclusion

Sorting tuples, lists of objects, or dictionaries by multiple criteria is straightforward in Python thanks to its lexicographic tuple comparison and the stability of its sort algorithm. So naturally, for homogeneous directions, a single key returning a tuple (or an itemgetter) suffices. These patterns give you fine‑grained control over ordering while keeping the code readable and efficient. So when you need different directions for different fields, either negate numeric fields within the key or perform two stable passes—sorting by the lower‑priority field first, then by the higher‑priority field with reverse=True. With these tools in hand, you can confidently tackle any multi‑level sorting task that arises in data processing, reporting, or algorithmic challenges That's the whole idea..

Out Now

Freshly Posted

On a Similar Note

A Natural Next Step

Thank you for reading about Python Sort A List Of Tuples. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home