Python Lambda Functions and Sorting With key=
A lambda is a tiny function written as an expression: lambda x: x * x takes one argument and returns its square. It has no name and no return keyword; the single expression after the colon is the return value. Lambdas are most useful as short throwaway arguments to other functions.
Lambda versus def
square = lambda x: x * x works, but style guides discourage assigning a lambda to a name, because def square(x): return x * x is just as short, gets a proper name in error messages, and can hold a docstring. Use a lambda only when the function is passed directly to something else and is too small to deserve a name.
Key functions
sorted(), list.sort(), min() and max() accept a key argument: a function that is called on each item to produce the value actually compared. The items themselves are returned unchanged.
key=str.lowersorts text case-insensitively. Notice in the example that plainsorted()puts"Fig"first, because uppercase letters have smaller character codes than lowercase ones.key=lensorts by length. Python's sort is stable: items with equal keys keep their original order.key=lambda w: w[-1]sorts by the last letter.key=lambda b: b[1]picks the second field of each tuple, somin()finds the cheapest book.
Expected output
49 ['Fig', 'apple', 'banana', 'cherry'] ['apple', 'banana', 'cherry', 'Fig'] ['Fig', 'apple', 'banana', 'cherry'] ['banana', 'apple', 'Fig', 'cherry'] Paper Cranes [22.0, 34.5, 25.0]
To sort by several criteria, return a tuple from the key, for example key=lambda p: (p.last, p.first). Tuples compare item by item, so the second field only breaks ties in the first.
map() and filter()
map(func, items) applies a function to every item, and filter(func, items) keeps the items for which the function returns a truthy value. Both return lazy iterators, so wrap them in list() to see the results. In modern Python, list comprehensions (next chapter) usually express the same idea more readably.
Common mistakes
- Trying to put statements, such as an assignment or
ifblock, inside a lambda. Only one expression is allowed; write adefinstead. - Calling the key yourself:
key=str.lower()is wrong. Pass the function, not its result. - Forgetting
reverse=Trueexists and negating keys by hand.
Summary
lambda args: expressioncreates a small anonymous function.key=tells sorting andmin/maxwhat to compare.- Python's sort is stable; return a tuple to sort by several fields.
Quiz: Lambda and sorting keys