logo

Higher-Order Functions

A higher-order function either takes a function as an argument or returns a function. You've already seen examples: map(), filter(), and sorted() all accept functions.

def apply_twice(func, x):
    return func(func(x))

def add_one(x):
    return x + 1

print(apply_twice(add_one, 5))  # 7

Functions that return functions are also common:

def multiplier(n):
    def multiply(x):
        return x * n
    return multiply

double = multiplier(2)
triple = multiplier(3)

print(double(5))  # 10
print(triple(5))  # 15

The inner function remembers the n value from when it was created. This is called a closure.

Higher-order functions are the foundation of functional programming. They let you write flexible, reusable code.

I explain closures and higher-order patterns in my Functional Programming course.