← All lessons

Higher-order functions

Sign in · Sign up

Lesson 11.7

A function can be passed to another function — it is a value like a number:

def apply(func, x):
    return ...           # call func with x


def double(x):
    return x * 2


print(apply(double, 5))  # 10
  • apply(double, 5) passes the function, not its result;
  • double() would work out 10 straight away — here you need the reference double;
  • key=len passes a function too: len(word) becomes the key.

The check sets the number value and the list words. Print two lines: the result of apply(double, value) for your own double, then words sorted by length.

Hint

A function can be passed by name, without brackets: apply(double, 5), not double(5).

Inside apply the call is func(x). For sorting by length there is key=len: the key is a function, and its result takes part in the comparison.