vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns str() in Python 2026: String Conversion + Modern Formatting & Best Practices type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns super() in Python 2026: Method Resolution & Modern Inheritance Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices round() in Python 2026: Rounding Numbers + Modern Precision & Use Cases reversed() in Python 2026: Reverse Iteration + Modern Patterns & Best Practices repr() in Python 2026: Official String Representation + Modern Debugging & Serialization Use Cases pow() in Python 2026: Power & Modular Exponentiation + Modern Use Cases & Best Practices property() in Python 2026: Properties, Getters/Setters & Modern Patterns ord() in Python 2026: Unicode Code Point from Character + Modern Use Cases & Best Practices open() in Python 2026: File Handling + Modern I/O Patterns & Best Practices range() in Python 2026: Efficient Sequence Generation + Modern Patterns & Best Practices print() in Python 2026: Output Formatting + Modern CLI & Debugging Patterns View all in this category →

sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices

Built In Function Mar 24, 2026

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?YesNo (in-place)sorted(): when original needed
Works on any iterable?YesNo (only lists)sorted(): tuples, generators, etc.
Memory usageO(n)O(1) extralist.sort(): memory-constrained
Stable sort?YesYesEqual
2026 preferenceMost casesWhen in-place is requiredsorted() 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:

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices