all Python 3Lists (list)term
Sorting with key= / lambda
sorting
key= takes a function that returns the value to compare by. A lambda is handy for one-line keys.
Syntax
sorted(lst, key=func) | lst.sort(key=lambda x: ...)
The key function is called exactly once per element, not on every comparison, so a moderately expensive key is cheaper than it looks. Sorting is stable: items with equal keys keep their original order, which is what makes multi-field sorting work as several passes from the least significant field to the most significant one (reverse=True preserves stability too). The classic slip is writing key=len() instead of key=len — you pass the function itself, not the result of calling it.
Examples
words = ['banana', 'apple', 'fig', 'cherry']
print(sorted(words, key=len))
# → ['fig', 'apple', 'banana', 'cherry']
pairs = [(2, 'b'), (1, 'c'), (3, 'a')]
print(sorted(pairs, key=lambda x: x[1]))
# → [(3, 'a'), (2, 'b'), (1, 'c')]
print(sorted(pairs, key=lambda x: x[0], reverse=True))
# → [(3, 'a'), (2, 'b'), (1, 'c')]
people = [('Alice', 30), ('Bob', 25), ('Carol', 30)]
print(sorted(people, key=lambda p: (p[1], p[0])))
# → [('Bob', 25), ('Alice', 30), ('Carol', 30)]
nums = ['-3', '1', '-10', '2']
print(sorted(nums, key=lambda x: abs(int(x))))
# → ['1', '2', '-3', '-10']
strs = ['Banana', 'apple', 'Cherry']
print(sorted(strs, key=str.lower))
# → ['apple', 'Banana', 'Cherry']
from operator import itemgetter
data = [{'name': 'b', 'val': 2}, {'name': 'a', 'val': 3}]
print(sorted(data, key=itemgetter('name')))
# → [{'name': 'a', 'val': 3}, {'name': 'b', 'val': 2}]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy