Functions are values
Here is the idea this whole lesson builds on: in Python, a function is a value, just like a number or a string. You can store it in a variable, put it in a list, or pass it to another function. A function that takes or returns another function is called a higher-order function.
def shout(text): return text.upper() + "!" say = shout # no parentheses: we pass the function itself print(say("hi")) # HI!
Writing shout hands over the function. Writing shout(...) calls it. That distinction matters everywhere below.
The payoff is immediate and practical: custom sort orders, leaderboards by score, files by size, orders by date, are all one key= away once you can hand one function to another.
sorted(key=...)
You used sorted(nums) in Python for Beginners. Its superpower is the key parameter: pass a function, and Python calls it on each item to decide the sort order, without changing the items:
words = ["pear", "fig", "banana"] sorted(words, key=len) # ['fig', 'pear', 'banana']
When the key is tiny and used once, defining a whole def is heavy. A lambda is a one-expression, inline function:
lambda w: w[-1] # takes w, returns its last character
lambda arguments: expression and nothing more. No statements, no return keyword, the expression is the return value.
Code exercise · python
Run this program. In the default string order every capital letter sorts before every lowercase letter, which is rarely what a user wants to see. key=str.lower sorts by a lowercase shadow of each string while returning the original strings untouched.
Code exercise · python
Run this program. Same list, three different orders, chosen purely by the key function.
Where you will meet this again
max(items, key=...)andmin(items, key=...)accept the samekeyidea.sorted(d.items(), key=lambda kv: kv[1])sorts a dict by value, a pattern you will use in the Counter lesson (6-1) and the capstone (unit 10).- Comprehensions from unit 1 usually beat
mapandfilter, but you should recognizemap(f, xs)andfilter(f, xs)when reading other people's code: they apply or testfone item at a time as you loop over the result, instead of all at once up front (unit 4 covers this on-demand style in depth).
One caution from the style police: if a lambda gets hard to read, promote it to a named def. Lambdas are for tiny keys, not logic.
Code exercise · python
Your turn. Sort the inventory dict by count, smallest first, and print each "name count" line in that order. Use sorted on inventory.items() with a lambda key.
Code exercise · python
Your turn. max accepts the same key= as sorted. Print the name and score of the top player using ONE max call with a lambda key, no sorting.
Quiz
What does sorted(["bb", "a", "ccc"], key=len) return?