Higher Order Functions in Python (With Examples)

Higher order functions in Python are functions that take another function as an argument, return a function, or both. You already use them: sorted(items, key=...), map() and filter() all accept a function:

sorted(orders, key=lambda o: o[1])     # sorted() takes a function
def make_discount(p):
    return lambda price: price * (1 - p / 100)   # returns a function

The output below is from Python 3.12.5, using small order and pricing data.

We’ll treat functions as values, pass them to built-ins, return them from other functions (closures), use functools, write a decorator, and dodge a classic gotcha.

Functions are values in Python

In Python, a function name is just a variable pointing at a function object, and you can treat it like one. You can store it, pass it around and call it later, which is the whole idea behind higher-order functions:

def add_tax(price):
    return round(price * 1.08, 2)

def apply_to_all(func, prices):            # a higher-order function: takes a function
    return [func(p) for p in prices]

f = add_tax                                 # functions are values you can store
print(f(10.00), type(f).__name__, f.__name__)
print(apply_to_all(add_tax, [4.50, 2.75, 19.99]))
print(apply_to_all(round, [4.50, 2.75, 19.99]))

Output:

10.8 function add_tax
[4.86, 2.97, 21.59]
[4, 3, 20]
Command Prompt output of a Python higher-order function applying add_tax and the built-in round to a list of prices
apply_to_all doesn’t care which function you give it; that’s what makes it reusable.

Notice there aren’t any parentheses when you pass add_tax. With parentheses you’d pass its result, not the function.

Built-in higher-order functions: sorted, map and filter

You’ll find many built-ins take a function to customize what they do. A short lambda is the usual way to write a throwaway function inline:

orders = [("Austin", 59.99), ("Denver", 120.00), ("Boston", 35.50), ("Tampa", 89.25)]

print(sorted(orders, key=lambda o: o[1]))                     # sorted takes a key function
print(max(orders, key=lambda o: o[1]))
print(list(map(lambda o: o[0].upper(), orders)))              # map applies a function
print(list(filter(lambda o: o[1] > 50, orders)))              # filter keeps matches
print([o[0] for o in orders if o[1] > 50])                    # the comprehension equivalent

Output:

[('Boston', 35.5), ('Austin', 59.99), ('Tampa', 89.25), ('Denver', 120.0)]
('Denver', 120.0)
['AUSTIN', 'DENVER', 'BOSTON', 'TAMPA']
[('Austin', 59.99), ('Denver', 120.0), ('Tampa', 89.25)]
['Austin', 'Denver', 'Tampa']
Command Prompt output of Python sorted and max with key functions, map and filter with lambdas, and a list comprehension
The last line does the same job as filter with a comprehension, which many people find easier to read.

I usually reach for comprehensions over map and filter, but key functions in sorted, min and max are everywhere. More on lambdas in lambda functions in Python.

Functions that return functions (closures)

You can also write a function that builds and returns another function. The inner function remembers the variables it was created with, which is called a closure:

def make_discount(percent):
    def apply(price):                      # this inner function "remembers" percent
        return round(price * (1 - percent / 100), 2)
    return apply                           # returning a function

black_friday = make_discount(30)
member = make_discount(10)

print(black_friday(80.00), member(80.00))
print(black_friday.__closure__[0].cell_contents, "percent is stored in the closure")

Output:

56.0 72.0
30 percent is stored in the closure
Command Prompt output of a Python function factory returning discount functions that remember their percentage in a closure
black_friday and member are two separate functions, each remembering its own percent.

Higher-order tools in functools: partial and reduce

I like partial for pre-filling arguments; it returns a new function. reduce repeatedly applies a two-argument function to fold a list into one value:

from functools import partial, reduce
import operator

def price_with(rate, price):
    return round(price * (1 + rate), 2)

texas = partial(price_with, 0.0625)        # pre-fill the first argument
california = partial(price_with, 0.0725)
print(texas(100.00), california(100.00))

cart = [19.99, 4.50, 102.00, 12.75]
print(reduce(operator.add, cart))          # fold a list down to one value
print(reduce(lambda a, b: a if a > b else b, cart))

Output:

106.25 107.25
139.24
102.0

For more on folding, see the reduce() function in Python. sum() and max() are usually clearer for the common cases.

What is a decorator in Python?

A decorator is a higher-order function that takes a function and returns an improved version. The @timed line is shorthand for build_report = timed(build_report):

import time
from functools import wraps

def timed(func):                           # takes a function, returns a new one
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.3f} s")
        return result
    return wrapper

@timed
def build_report(n):
    return sum(i * i for i in range(n))

print(build_report(2_000_000))
print(build_report.__name__)               # wraps keeps the original name

Output:

build_report took 0.112 s
2666664666667000000
build_report
Command Prompt output of a Python timing decorator wrapping a function and preserving its name with functools.wraps
The wrapper times the call and returns the original result; @wraps keeps the function’s name and docstring.

Decorators work on classes too; see Python class decorators.

A higher-order function gotcha: late binding in loops

If you create lambdas in a loop, they look up the loop variable when they run, not when they’re created, so they all end up using the last value:

multipliers = [lambda x: x * n for n in range(1, 4)]
print([m(10) for m in multipliers])        # all use the last n!

multipliers = [lambda x, n=n: x * n for n in range(1, 4)]   # bind n now with a default
print([m(10) for m in multipliers])

Output:

[30, 30, 30]
[10, 20, 30]

Binding the value as a default argument, n=n, captures it at creation time. functools.partial works too.

Higher-order functions at a glance

ToolTakes a function?Returns a function?
sorted(key=...), min, maxYesNo
map, filterYesNo (returns an iterator)
functools.reduceYesNo
functools.partialYesYes
DecoratorsYesYes
Closures / function factoriesSometimesYes

Related function guides:

Frequently asked questions

What are higher order functions in Python?

Functions that take another function as an argument, return a function, or both, such as sorted(key=...), map() and decorators.

Is map a higher-order function?

Yes. map(func, items) takes a function and applies it to every item.

What’s the difference between a closure and a higher-order function?

A higher-order function works with functions. A closure is an inner function that remembers variables from where it was created; returning one is a common higher-order pattern.

Should I use map and filter or comprehensions?

Comprehensions are usually clearer in Python. Use map when you already have a named function to apply.

Why do all my loop lambdas return the same value?

They look up the loop variable when called. Bind it with a default argument like lambda x, n=n: x * n.

Where can I read more about functional programming in Python?

See the Functional Programming HOWTO in the Python docs.