← All lessons
Python advanced · Lesson 6 of 11

Functions as values

In Python a function is an object like any other. You can store it in a variable, put it in a list or dict, pass it to another function, and return it from one. A function that takes or returns functions is called a higher-order function.

def shout(s):
    return s.upper()

def whisper(s):
    return s.lower()

styles = {"loud": shout, "quiet": whisper}
for name, fn in styles.items():
    print(name, fn("Hello"))
Prints
loud HELLO
quiet hello

Note shout without brackets is the function itself; shout("x") calls it. For a tiny function used once, lambda writes it inline: lambda x: x * 2 is a function of x that returns x * 2. It can hold only a single expression.

The most common place for one is the key argument of sorted(), min() and max(): a function applied to each item to decide the order. reverse=True flips it.

people = [("Ana", 31), ("Ben", 27), ("Cy", 35)]
print(sorted(people, key=lambda p: p[1]))
print(max(people, key=lambda p: p[1])[0])
print(sorted(["kiwi", "Fig", "apple"], key=str.lower))
Prints
[('Ben', 27), ('Ana', 31), ('Cy', 35)]
Cy
['apple', 'Fig', 'kiwi']

map(fn, items) applies a function to every item and filter(fn, items) keeps the items it returns True for. Both are lazy, like generators. Comprehensions usually read better, but you'll see both in other people's code.

print(list(map(len, ["a", "bb", "ccc"])))
print(list(filter(lambda n: n % 2, range(6))))
Prints
[1, 2, 3]
[1, 3, 5]

A function defined inside another can use the outer function's variables, even after the outer one has returned. It carries them with it. That's called a closure, and it's a neat way to make functions to order. (nonlocal lets the inner function assign to one of those variables.)

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

triple = make_multiplier(3)
print(triple(5), make_multiplier(10)(2))
Prints
15 20

functools has the classic tools. partial fixes some arguments of a function to make a new one; reduce folds a list into one value by applying a function pairwise; cache (or lru_cache, which can limit its size) remembers a function's results so repeated calls with the same arguments are instant, which is called memoisation.

from functools import partial, reduce, cache

int_from_binary = partial(int, base=2)
print(int_from_binary("1010"))
print(reduce(lambda a, b: a * b, [1, 2, 3, 4]))

@cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))
Prints
10
24
23416728348467685

Without the cache, fib(80) would make more calls than there are grains of sand on Earth; with it, each value is worked out once.

Practice

What does this print?

f = lambda a, b: a * 10 + b
print(f(4, 2))
More info

Quick reference

fn vs fn()The function object / calling it.
lambda x: exprA small one-expression function.
sorted(xs, key=f, reverse=True)Sort by f(item); also for min and max.
map / filterApply a function to each / keep items where it's True (lazy).
closureAn inner function that keeps the outer function's variables.
functools.partial / reduce / cacheFix arguments / fold a list / remember results.

Related courses