Python · Functions & Decorators

What is a higher-order function?

Mediumhigher-orderfunctionsmapfilterdecorators

Interview question

What is a higher-order function?

How to answer

The short answer

A higher-order function (HOF) is a function that takes another function as an argument, returns a function, or both. Decorators, map, filter, sorted(..., key=...), and many callback APIs are HOFs.

This style is natural in Python because functions are first-class objects.

Python
def apply_twice(fn, x):
    return fn(fn(x))

print(apply_twice(lambda n: n + 1, 3))  # 5

def with_prefix(prefix):
    def formatter(text):
        return f"{prefix}{text}"
    return formatter          # returns a function

error = with_prefix("ERROR: ")
print(error("disk full"))

nums = [3, 1, 2]
print(sorted(nums, key=lambda n: -n))
print(list(map(str, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))

Why interviewers ask: It checks whether you understand functions as values, which underpins decorators, closures, and clean pipeline code.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill