Sorting Lists in Python: Comparing sort() and sorted()
Python supports two primary mechanisms for ordering list elements: the in‑place list.sort method and the built‑in sorted function. While both accept the same keyword parameters—key, reverse—sorted always returns a new list, whereas sort mutates the original in place and returns None.
Function Signatures
sorted(iterable, /, *, key=None, reverse=False)
list.sort(*, key=None, reverse=False)
- iterable – any iterable (
sortedonly). - key – a callable that extracts a comparison value from each element.
- reverse –
Truefor descending order,False(default) for ascending.
Basic Numeric Ordering
values = [9, 2, 7, 1, 4]
# Create a new sorted list
ordered = sorted(values) # [1, 2, 4, 7, 9]
# Sort in place
values.sort() # values is now [1, 2, 4, 7, 9]
Sorting with a Key Function
The key parameter accepts any callable that receives a single element and returns the value used for comparison.
pairs = [('b', 5), ('d', 1), ('c', 3), ('a', 2)]
# Order by the numeric second element only
result = sorted(pairs, key=lambda item: item[1])
# [('d', 1), ('a', 2), ('c', 3), ('b', 5)]
Multi‑Level Sorting
When a sequence of tuples is passed as the key, Python compares element by element, enabling stible multi‑criteria sorts.
records = [('x', 4), ('a', 2), ('y', 2), ('b', 3)]
# Primary sort by second element, secondary by first
arranged = sorted(records, key=lambda r: (r[1], r[0]))
# [('a', 2), ('y', 2), ('b', 3), ('x', 4)]
Descanding Order with reverse
numbers = [5, 2, 3, 1, 4]
desc_sorted = sorted(numbers, reverse=True) # [5, 4, 3, 2, 1]
items = ['c', 'a', 'b']
items.sort(reverse=True) # items → ['c', 'b', 'a']
Performance Note
Using the key parameter is generally more efficient than providing a custom comparison function, because each element’s key is computed only once rather than during every pairwise evaluation.