September 2026
1051 pages
35h 4m
English
When sorting a list using the built-in sorted function, a function can be passed that describes the ordering of the elements. In this way, the elements can be sorted according to self-defined criteria:
>>> def s(x):... return -x... >>> sorted([1,4,7,3,5], key=s)[7, 5, 4, 3, 1]
In this case, the function s has been defined to negate a passed value, thus sorting the list in descending order. Functions like s used in such or similar contexts are usually very simple and are defined, used, and then forgotten.
Using the lambda keyword, a small anonymous function can be created instead:
>>> s = lambda x: -x
The lambda keyword is followed by a parameter list and a colon. The colon must be followed by any arithmetic or ...
Read now
Unlock full access