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.
Python code
10 linesdef 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
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
- Use `operator.itemgetter(1)` instead of a lambda for faster performance on large lists
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.