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.

0 / 78 solved

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

  1. 89A function is a valuedouble = lambda x: x * 2. A function goes into a variable just like a number or a string.Go to the exercises
  2. 90Hand over what to sort bysorted(names, key=len). Leaving the parentheses off len is the whole of it.Go to the exercises
  3. 91Find the best in one linemax(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

  1. 92Do the same thing to everythingmap(f, xs) transforms the lot in one go. Forget the list and you see nothing — that is the trap.Go to the exercises
  2. 93Keep only what matchesfilter(f, xs) asks a function whether each one stays. This one needs list too before you can see it.Go to the exercises
  3. 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

Next up is “More handy tools”. Sets, collections, regular expressions and recursion. Tools that suddenly make life easier, each with the reason you would want it.