tuple sorting
Python programming
data manipulation
sorting algorithms
programming tutorial

Sorting a tuple based on one of the fields

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Sorting tuples by one field in Python is usually a sorted(..., key=...) problem. The core idea is simple: tell Python which tuple position matters for ordering, and let the built-in sort handle the rest.

Core Sections

Sort by one tuple position

Suppose each tuple is (name, age), and you want to sort by age. The normal solution is a key function that returns the second element.

python
1people = [
2    ("Alice", 31),
3    ("Bob", 24),
4    ("Carol", 29),
5]
6
7result = sorted(people, key=lambda person: person[1])
8print(result)

Output:

text
[('Bob', 24), ('Carol', 29), ('Alice', 31)]

The tuples themselves are not changed. sorted returns a new list ordered by the value returned from the key function.

Use itemgetter for clarity

For tuple-like data, operator.itemgetter often reads more cleanly than a lambda.

python
1from operator import itemgetter
2
3people = [
4    ("Alice", 31),
5    ("Bob", 24),
6    ("Carol", 29),
7]
8
9result = sorted(people, key=itemgetter(1))
10print(result)

This does the same thing as lambda person: person[1]. It is mostly a readability choice, but it is common Python style for simple tuple sorting.

Ascending versus descending order

Sorting defaults to ascending order. To reverse it, add reverse=True.

python
1scores = [
2    ("a", 80),
3    ("b", 95),
4    ("c", 88),
5]
6
7descending = sorted(scores, key=lambda row: row[1], reverse=True)
8print(descending)

That is better than negating numeric values manually because it keeps the intent obvious.

Sort by multiple fields

If the target field can tie, return a tuple key. Python compares tuple keys left to right.

python
1records = [
2    ("Bob", 24),
3    ("Alice", 24),
4    ("Carol", 29),
5]
6
7result = sorted(records, key=lambda row: (row[1], row[0]))
8print(result)

Output:

text
[('Alice', 24), ('Bob', 24), ('Carol', 29)]

Here the primary sort is age and the secondary sort is name.

Sorting a tuple of tuples

If the outer container is itself a tuple, sorted still returns a list because sorting creates a new ordered sequence.

python
1data = (
2    ("x", 3),
3    ("y", 1),
4    ("z", 2),
5)
6
7sorted_data = sorted(data, key=lambda row: row[1])
8print(sorted_data)
9print(type(sorted_data))

If you really need a tuple back, convert afterward:

python
sorted_tuple = tuple(sorted(data, key=lambda row: row[1]))

That distinction matters because the question is often phrased as "sort a tuple," but Python's sort operation returns a list unless you convert it.

sorted() versus .sort()

Use sorted() when:

  • the input might not already be a list
  • you want to preserve the original container
  • you prefer an expression that returns a new object

Use .sort() when you already have a list and want to reorder it in place.

python
rows = [("x", 3), ("y", 1), ("z", 2)]
rows.sort(key=lambda row: row[1])
print(rows)

That avoids allocating another list, but only works on mutable lists.

Common Pitfalls

  • Forgetting that sorted() returns a new list rather than modifying the original data.
  • Using the wrong tuple index and sorting by the wrong field.
  • Assuming the result keeps tuple type when the input container is a tuple; sorted() still returns a list.
  • Writing a complex lambda when itemgetter or a tuple key would be clearer.
  • Ignoring ties and then being surprised when equal primary values are not ordered the way you expected.

Summary

  • Use sorted(data, key=lambda row: row[index]) to sort tuples by one field.
  • 'itemgetter(index) is a clean alternative for simple tuple indexing.'
  • Add reverse=True for descending order.
  • Return a tuple key when you need secondary sort behavior.
  • Remember that sorted() always returns a list, even if the original container was a tuple.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.