CHAPTER 10 · 6 lessons · 78 exercises
Higher-order functions and lambdas
Pass a function as a value. Once the work itself can be an argument, what you are able to write changes.
When you met functions in Chapter 3, a function was something you called. This chapter turns that round. A function is a value.
Just like a number or a string, it can go in a variable, be handed to another function, or be handed back. A function that takes or returns functions is called a higher-order function.
Sorting is where you feel it first. sorted(names) just sorts, but the moment you want them shortest-first you have to tell it what to sort by. So you write sorted(names, key=len), passing the function len as a value. Notice there are no parentheses on it — put them there and you would be passing the *result of calling it*. Without them, it is the function itself.
When the rule only matters here and now, giving it a name with def is heavy-handed. That is what a lambda is for. Write lambda x: x["age"] and you have a small nameless function on the spot. sorted(people, key=lambda p: p["age"]) sorts by age.
After that come map and filter. map applies the same work to everything; filter keeps only what matches. They do very nearly what a comprehension does, and in Python the comprehension is usually preferred. We cover them anyway, because they show up in other people's code. Be able to read both.
The chapter ends on the idea itself: passing a function as an argument. Once you can write "what happens next is up to whoever calls me", how you build a reusable piece changes. If you have done any JavaScript, you will recognise this as the same conversation as callbacks.
Lessons in this chapter
Functions with no name
- 89A function is a value
double = lambda x: x * 2. A function goes into a variable just like a number or a string.Go to the exercises - 90Hand over what to sort by
sorted(names, key=len). Leaving the parentheses offlenis the whole of it.Go to the exercises - 91Find the best in one line
max(register, key=lambda p: p["score"]). That shape you spent five lines on in chapter 2 becomes one.Go to the exercises
Pass a function in
- 92Do the same thing to everything
map(f, xs)transforms the lot in one go. Forget thelistand you see nothing — that is the trap.Go to the exercises - 93Keep only what matches
filter(f, xs)asks a function whether each one stays. This one needslisttoo before you can see it.Go to the exercises - 94Write a function that takes a functionWhat happens next is for the caller to decide. It changes how you build a piece.Go to the exercises