I saw some examples using built-in functions like sorted, sum etc. that use key=lambda.
What does lambda mean here? How does it work?
For the general computer science concept of a lambda, see What is a lambda (function)?.
See also How are lambdas useful? for some discussion that no longer meets site standards but which you may find useful.
A
lambdais an anonymous function:It is often used in functions such as
sorted()that take a callable as a parameter (often thekeykeyword parameter). You could provide an existing function instead of alambdathere too, as long as it is a callable object.Take the
sorted()function as an example. It’ll return the given iterable in sorted order:but that sorts uppercased words before words that are lowercased. Using the
keykeyword you can change each entry so it’ll be sorted differently. We could lowercase all the words before sorting, for example:We had to create a separate function for that, we could not inline the
def lowercased()line into thesorted()expression:A
lambdaon the other hand, can be specified directly, inline in thesorted()expression:Lambdas are limited to one expression only, the result of which is the return value.
There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.