sorted()Advanced Examples

Returns a new sorted list from any iterable

sorted() protocol implementation

Implementing the protocol that sorted() uses under the hood.

python
# Custom sorting with protocol
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius
    def __lt__(self, other):
        return self.celsius < other.celsius
    def __repr__(self):
        return f"Temp({self.celsius}°C)"

temps = [Temperature(30), Temperature(20), Temperature(25)]
print(sorted(temps))

Understanding the dunder methods that sorted() calls helps you customize behavior for your own classes.

Edge cases with sorted()

Handling unusual inputs and edge cases.

python
# sorted() edge cases
print("Edge case handling for sorted()")

# Type checking
print(type(42))

Knowing these edge cases prevents subtle bugs in production.

Want to try these examples interactively?

Open Advanced Playground