transformation
sorted()
Returns a new sorted list from any iterable. Uses Timsort — stable, O(n log n).
sorted(iterable, *, key=None, reverse=False) Parameters
| Parameter | Purpose |
|---|---|
| key | Function extracting a comparison key from each element |
| reverse | Sort descending when True |
Examples
sorted([3, 1, 2]) Returns [1, 2, 3]
sorted(['bb', 'a', 'ccc'], key=len) Returns ['a', 'bb', 'ccc']
sorted([{'n': 2}, {'n': 1}], key=lambda d: d['n']) Returns [{'n': 1}, {'n': 2}]
sorted('hello', reverse=True) Returns ['o', 'l', 'l', 'h', 'e']
Gotcha
Unlike list.sort(), sorted() always returns a new list and works on any iterable. Mixing types (e.g., int and str) raises TypeError.
Related built-ins
min()
Returns the smallest item in an iterable or the smallest of two or more arguments. Supports a key function for custom comparison.
max()
Returns the largest item in an iterable or the largest of two or more arguments. Supports a key function for custom comparison.
sum()
Sums the items of an iterable, adding them to start. Optimized for numbers.
any()
Returns True if any element of the iterable is truthy. Short-circuits on the first truthy value.
all()
Returns True if every element of the iterable is truthy (or if the iterable is empty). Short-circuits on the first falsy value.