Built-in Functions
sorted and reversed
Sorting iterables with custom keys and reversing sequences
Interview: Very common — stable sort, multi-key sorting, and custom key functions are frequently tested
sorted() returns a new sorted list from any iterable, while reversed() returns an iterator that yields elements in reverse order. Python's sort uses Timsort — a stable, adaptive algorithm that is O(n log n) worst case but very fast on real-world data.
sorted() Function
- Returns new list: Unlike list.sort() which sorts in-place, sorted() always creates a new list
- Works on any iterable: Lists, tuples, strings, dicts (keys), generators — all work
- key parameter: A function called on each element for comparison —
key=len,key=str.lower - reverse parameter:
reverse=Truefor descending order - Stable sort: Equal elements maintain their original relative order — crucial for multi-key sorting
Multi-Key Sorting
- Tuple key:
key=lambda x: (x.age, x.name)— sorts by age first, then name - Mixed order:
key=lambda x: (-x.score, x.name)— descending score, ascending name (for numbers) - Multiple passes: Sort by secondary key first, then primary — works because sort is stable
reversed() Function
- Returns iterator: Not a list — use
list(reversed(seq))if you need a list - Works on sequences: Lists, tuples, strings, range — anything with __reversed__ or indexing
- vs slicing:
reversed(lst)returns iterator;lst[::-1]returns a new list
sorted() vs list.sort()
sorted(iterable) works on any iterable and returns a new list. list.sort() only works on lists but modifies in-place (slightly faster, no extra memory). Use sorted() by default; use .sort() only when you specifically want in-place sorting.
Use Cases
Sorting complex data structures by multiple criteria
Ranking and leaderboard generation with multi-key sorting
Data cleaning and preprocessing pipelines
Displaying sorted results in APIs and reports
Implementing priority queues and ordered collections
Common Mistakes
Using list.sort() and assigning the result — it returns None, not the sorted list
Forgetting that sorted() returns a list even for strings/tuples input
Not knowing sort is stable — you can rely on equal elements keeping their order
Using reverse=True when you need mixed ascending/descending — use negation (-x) for numbers
Forgetting that reversed() returns an iterator, not a list — need list() to materialize