How to Sort a List of Tuples by the Second Element in Python

Sorts a list of tuples by the second element using the sorted() function with a lambda key, preserving the original list.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

10 lines
Python 3.9+
def sort_tuples_by_second(tuples_list):
    """Sort a list of tuples by the second element."""
    return sorted(tuples_list, key=lambda x: x[1])


if __name__ == "__main__":
    data = [(1, 5), (3, 2), (2, 8), (4, 1)]
    sorted_data = sort_tuples_by_second(data)
    print("Original list:", data)
    print("Sorted by second element:", sorted_data)

Output

stdout
Original list: [(1, 5), (3, 2), (2, 8), (4, 1)]
Sorted by second element: [(4, 1), (3, 2), (1, 5), (2, 8)]

How it works

The sorted() function returns a new list without modifying the original, which keeps the input data intact. The key parameter tells sorted() how to extract the comparison value from each tuple — here a lambda accesses the second element with x[1]. Sorting is stable, so tuples with equal second elements keep their original order. This works with any sequence of indexable objects, not just tuples.

Common mistakes

  • Using `list.sort()` when you need to preserve the original list — use `sorted()` instead
  • Forgetting that tuples are 0-indexed, so `x[1]` is the second element, not `x[2]`
  • Assuming the sort modifies the original list in place when using `sorted()`

Variations

  1. Use `operator.itemgetter(1)` instead of a lambda for faster performance on large lists
  2. Use `sorted(tuples_list, key=lambda x: x[1], reverse=True)` to sort in descending order

Real-world use cases

  • Ranking leaderboard entries by score where each tuple stores player ID and score.
  • Ordering log records by timestamp when each tuple contains a message and its epoch time.
  • Sorting product inventory by price in a tuple list before presenting data to users.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.