Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. What is a higher-order function?

Python · Functions & Decorators

What is a higher-order function?

Mediumpython-19
higher-orderfunctionsmapfilterdecorators

Question

What is a higher-order function?

Solution

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.

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.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext