key function
A function given as key= to sorted, sort, min or max, which turns each item into the value to compare by.
In more detail
Python calls the key function once per item and sorts by the results, so an expensive key is not recomputed at every comparison. For example, key=len sorts by length and key=str.lower sorts ignoring case. Returning a tuple sorts by several fields at once.
Related terms
- sorted() and list.sort() — Python's built-in sorts: sorted() returns a new sorted list from any iterable, and list.sort() sorts a list in place.
- operator.itemgetter — Functions from Python's operator module that build key functions: itemgetter fetches items by index or key and attrgetter fetches attributes.
- lexicographic order — Ordering sequences the way a dictionary orders words: compare the first elements, and only if they are equal move on to the next.
- sorted() — sorted(items) returns a new sorted list from any iterable; items.sort() sorts a list in place and returns None.
- lambda — A small function written inline as an expression, such as lambda x: x * 2, with no name and a single expression as its body.
- min() and max() — Built-in functions that return the smallest or largest item of an iterable, or of several arguments; sum adds them up.
Taught in
- Sorting In Real Systems: Stability, Keys And External Sort — Algorithms & Data Structures for Working Engineers
- Sorting, Keys And Lambdas — Hands-on Python: Complete Video Course & Book
- Iterators And Generators — Hands-on Python: Complete Video Course & Book