sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices
The built-in sorted() function returns a new sorted list from the items in an iterable — the safe, non-destructive alternative to list.sort(). In 2026 it remains one of the most commonly used built-ins for ranking, ordering data, preparing ML inputs, creating sorted views, leaderboard generation, and any scenario requiring sorted output without modifying the original collection.
With Python 3.12–3.14+ improving sorting performance (faster Timsort), better type hinting for sorted results, and free-threading compatibility for concurrent sorting (when used safely), sorted() is more efficient and type-safe than ever. This March 24, 2026 update covers how sorted() works today, real-world patterns, key argument usage (key=, reverse=), performance notes, and best practices for readable, performant, and type-safe sorting in modern Python.
TL;DR — Key Takeaways 2026
sorted(iterable, key=None, reverse=False)→ returns new sorted list- Stable sort (Timsort) — preserves relative order of equal elements
- 2026 best practice: Always use key= for custom sorting; prefer sorted() over list.sort() unless in-place is required
- Main use cases: ranking, data preparation, ML feature ordering, leaderboard, sorted display
- Type-safe pattern:
sorted(Iterable[T], key=Callable[[T], Comparable]) -> list[T] - Performance: O(n log n) — highly optimized C implementation
1. Basic Usage — Sorting Iterables
numbers = [64, 34, 25, 12, 22, 11, 90]
print(sorted(numbers)) # [11, 12, 22, 25, 34, 64, 90]
# Reverse order
print(sorted(numbers, reverse=True)) # [90, 64, 34, 25, 22, 12, 11]
# With key function
names = ["alice", "Bob", "Charlie", "dave"]
print(sorted(names, key=str.upper)) # ['alice', 'Bob', 'Charlie', 'dave']
print(sorted(names, key=len)) # ['Bob', 'dave', 'alice', 'Charlie']
2. Real-World Patterns in 2026
Ranking / Leaderboard (with key=)
def leaderboard(players: list[dict]) -> list[dict]:
return sorted(players, key=lambda p: p["score"], reverse=True)
scores = [
{"name": "Alice", "score": 950},
{"name": "Bob", "score": 1200},
{"name": "Charlie", "score": 800},
]
print(leaderboard(scores))
# [{'name': 'Bob', 'score': 1200}, {'name': 'Alice', 'score': 950}, {'name': 'Charlie', 'score': 800}]
ML Feature / Batch Sorting (NumPy/JAX)
import numpy as np
def sort_by_confidence(preds: np.ndarray, data: list) -> list:
indices = np.argsort(preds)[::-1] # descending
return [data[i] for i in indices]
conf = np.array([0.12, 0.95, 0.45])
items = ["low", "high", "medium"]
print(sort_by_confidence(conf, items))
# ['high', 'medium', 'low']
Multi-key Sorting (using tuple key)
students = [
("Alice", 31, "A"),
("Bob", 25, "B"),
("Charlie", 31, "A"),
]
# Sort by age desc, then grade asc
sorted_students = sorted(students, key=lambda s: (-s[1], s[2]))
print(sorted_students)
# [('Alice', 31, 'A'), ('Charlie', 31, 'A'), ('Bob', 25, 'B')]
3. sorted() vs list.sort() – Comparison 2026
| Feature | sorted() | list.sort() | Best For |
|---|---|---|---|
| Returns new list? | Yes | No (in-place) | sorted(): when original needed |
| Works on any iterable? | Yes | No (only lists) | sorted(): tuples, generators, etc. |
| Memory usage | O(n) | O(1) extra | list.sort(): memory-constrained |
| Stable sort? | Yes | Yes | Equal |
| 2026 preference | Most cases | When in-place is required | sorted() wins for safety |
4. Best Practices & Performance in 2026
- Prefer sorted() over list.sort() — returns new list, safer, works on more types
- Use key= for custom sorting — clearer than multiple sorted() calls
- Type hints 2026:
from typing import Iterable, TypeVar, Callable T = TypeVar("T") C = TypeVar("C") def sorted_by_key(it: Iterable[T], key: Callable[[T], C]) -> list[T]: return sorted(it, key=key) - Performance: O(n log n) — highly optimized Timsort
- Free-threading (3.14+): Safe for read-only sorting; use locks if modifying source
Conclusion — sorted() in 2026: Sorting Essential
sorted() is Python’s clean, stable, and versatile way to create sorted views of data — perfect for ranking, preprocessing, reporting, and algorithm implementation. In 2026, use it with key= for custom ordering, default= for empty safety, and type hints for clarity. It’s fast, readable, and one of Python’s most important tools for data manipulation, ML pipelines, and decision logic — especially when paired with min(), max(), and comprehensions.
Next steps:
- Replace any manual sorting loop with sorted() + key=
- Related articles: Efficient Python Code 2026 • Python Built-ins Overview 2026