Functions and order

Lesson 4 of 20 · Functional Python: values, behavior, and choices

Python functions are values: they can be stored, passed to another function, or returned. A function accepting or returning a function is called higher-order. Pass the function itself, not the result of calling it.

def distance(name):
    return len(name)

places = ["delta", "bay", "riverbank"]
print(sorted(places, key=distance))
print(sorted(places, key=lambda name: len(name)))
print(places)
['bay', 'delta', 'riverbank']
['bay', 'delta', 'riverbank']
['delta', 'bay', 'riverbank']

sorted calls the key function on each item and returns the original items in key order in a new list. distance is passed without parentheses. lambda name: len(name) creates a function whose single expression supplies its result. Prefer a named function when the operation needs explanation or reuse.

Pairing uses a different higher-order building block:

names = ["delta", "bay", "riverbank"]
levels = [4, 2]
print(list(zip(names, levels)))
[('delta', 4), ('bay', 2)]

zip yields tuples in position order and normally stops at the shortest input, leaving riverbank unpaired. Python 3.10+ supports zip(names, levels, strict=True) to raise ValueError when consumption discovers unequal lengths. zip is an iterator-producing function, not itself higher-order: it does not receive or return a function.

Chapter index