Higher-Order Functions
Published by Brayan K
Master the core functional programming techniques that power Python frameworks, AI pipelines, backend logic, decorators, and more.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Functions are values: keep them in dictionaries and lists
Functions showed that a function's name without brackets is the function itself, a value like any other. *args & **kwargs passed one to another function, and Lambda Functions passed them as key=. A function that takes a function, or returns one, is called a higher-order function. Being values, functions can also sit in a dictionary, which can replace a long if/elif chain:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
operations = {"+": add, "-": subtract, "*": multiply}
for symbol in ["+", "-", "*"]:
print(7, symbol, 3, "=", operations[symbol](7, 3))
# ✅ Expected output:
# 7 + 3 = 10
# 7 - 3 = 4
# 7 * 3 = 21operations[symbol] looks up a function, and (7, 3) calls it. A symbol with no entry raises a KeyError, as in Dictionaries. The classic slip is writing the brackets when you build the dictionary: that stores each call's result, not the function.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
operations = {"+": add(7, 3), "-": subtract(7, 3)}
print(operations)
print(operations["+"](7, 3))
# ✅ Expected output:
# {'+': 10, '-': 4}
# ✅ Expected error:
# TypeError: 'int' object is not callableA list of functions works the same way. str.title is a method taken from its class, which is a function that expects the string as its argument, as Object-Oriented Programming showed with Dog.bark(rex):
def shout(text):
return text.upper() + "!"
def whisper(text):
return text.lower() + "..."
for style in [shout, whisper, str.title]:
print(style("hello there"))
# ✅ Expected output:
# HELLO THERE!
# hello there...
# Hello ThereWriting a function that takes a function
A parameter can receive a function like any other value, and the body calls it with brackets:
def apply_twice(func, value):
return func(func(value))
def add_three(n):
return n + 3
print(apply_twice(add_three, 10))
print(apply_twice(str.upper, "hi"))
# ✅ Expected output:
# 16
# HIPass the function, not a call. With brackets, add_three(1) runs first and apply_twice receives its result, 4, which it then tries to call:
def apply_twice(func, value):
return func(func(value))
def add_three(n):
return n + 3
print(apply_twice(add_three(1), 10))
# ✅ Expected error:
# TypeError: 'int' object is not callableIt's the mistake Lambda Functions showed with key=len(), now in a function of your own. A function parameter makes a function general: count_if counts whatever its test says, and the test can be a named function or a lambda.
def count_if(values, test):
total = 0
for value in values:
if test(value):
total += 1
return total
def is_long(word):
return len(word) > 4
words = ["fig", "banana", "kiwi", "cherry", "apricot"]
print(count_if(words, is_long))
print(count_if(words, lambda w: w.startswith("c")))
print(count_if([3, -1, 4], lambda n: n > 0))
# ✅ Expected output:
# 3
# 1
# 2A test that forgets its return doesn't fail. It returns None, which counts as false, every time:
def count_if(values, test):
total = 0
for value in values:
if test(value):
total += 1
return total
def is_long(word):
len(word) > 4
print(count_if(["fig", "banana", "cherry"], is_long))
# ✅ Expected output:
# 0Function factories: functions that make functions
A function can define another function inside it and return it. Each call makes a new function, set up by the arguments it was given, which is why such a function is called a factory:
def make_multiplier(factor):
def multiply(n):
return n * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5))
print(make_multiplier(10)(4))
# ✅ Expected output:
# 10 15
# 40make_multiplier(10)(4) makes a function and calls it at once. The functions it makes are ordinary functions, all named multiply; their full name says where they were made:
def make_multiplier(factor):
def multiply(n):
return n * factor
return multiply
double = make_multiplier(2)
print(double.__name__)
print(double.__qualname__)
print(type(double))
# ✅ Expected output:
# multiply
# make_multiplier.<locals>.multiply
# <class 'function'>make_multiplier.<locals>.multiply means multiply, defined inside make_multiplier. That full name appears in error messages, such as when the factory calls the function instead of returning it:
def make_multiplier(factor):
def multiply(n):
return n * factor
return multiply()
double = make_multiplier(2)
# ✅ Expected error:
# TypeError: make_multiplier.<locals>.multiply() missing 1 required positional argument: 'n'A factory with no return at all returns None, and the error waits for the first call:
def make_multiplier(factor):
def multiply(n):
return n * factor
double = make_multiplier(2)
print(double)
print(double(5))
# ✅ Expected output:
# None
# ✅ Expected error:
# TypeError: 'NoneType' object is not callableWhat the returned function keeps
multiply uses factor long after make_multiplier has finished. Python keeps the outer function's variables alive for the inner function that uses them, separately for each call, though they stay invisible outside:
def make_greeting(greeting):
def greet(name):
return greeting + ", " + name + "!"
return greet
hello = make_greeting("Hello")
howdy = make_greeting("Howdy")
print(hello("Ada"))
print(howdy("Ada"))
print(greeting)
# ✅ Expected output:
# Hello, Ada!
# Howdy, Ada!
# ✅ Expected error:
# NameError: name 'greeting' is not definedThe inner function keeps the variable, not a copy of its value, and reads it when it runs. Change the list after the factory call, and the function sees the change:
def make_report(names):
def report():
return ", ".join(names)
return report
team = ["Ada", "Grace"]
show = make_report(team)
team.append("Linus")
print(show())
# ✅ Expected output:
# Ada, Grace, LinusA function that keeps variables from the function it was made in is called a closure. Closures & Lexical Scope in Real Projects covers the rest: changing those variables from inside, and why functions made in a loop all see the loop's last value, which Lambda Functions mentioned.
Composing functions into pipelines
A factory can take functions and return one that runs them in turn. compose(f, g) follows the maths order: the inner one, g, runs first:
def compose(f, g):
def both(x):
return f(g(x))
return both
def double(n):
return n * 2
def add_one(n):
return n + 1
print(compose(double, add_one)(3))
print(compose(add_one, double)(3))
# ✅ Expected output:
# 8
# 7With *steps, a pipeline takes any number of functions and runs them left to right, which reads more naturally for a list of steps:
def pipeline(*steps):
def run(value):
for step in steps:
value = step(value)
return value
return run
slug = pipeline(str.strip, str.lower, lambda s: s.replace(" ", "-"))
print(slug(" Hello World "))
print(pipeline()(42))
# ✅ Expected output:
# hello-world
# 42With no steps, the pipeline hands its value straight back. A step written with brackets is called while the pipeline is being built, with nothing to work on:
def pipeline(*steps):
def run(value):
for step in steps:
value = step(value)
return value
return run
slug = pipeline(str.strip, str.lower())
# ✅ Expected error:
# TypeError: unbound method str.lower() needs an argumentA factory that makes key functions
Sorting records by different fields needs a different key= each time. Instead of a new lambda for each, a factory can make the key function from a field name:
def by(field):
def get(record):
return record[field]
return get
people = [
{"name": "Grace", "age": 45},
{"name": "Linus", "age": 29},
{"name": "Ada", "age": 36},
]
print([p["name"] for p in sorted(people, key=by("age"))])
print([p["name"] for p in sorted(people, key=by("name"))])
print(max(people, key=by("age"))["name"])
# ✅ Expected output:
# ['Linus', 'Ada', 'Grace']
# ['Ada', 'Grace', 'Linus']
# GraceThe standard library has this one ready-made, as operator.itemgetter("age"): Sorting with sorted() & key uses it, and The operator Module covers the rest of the module.
A function that wraps another
A factory that takes a function can return a new function that does something extra around it. Here is the logged() from *args & **kwargs, now returning a function that logs every call it passes on:
def logged(func):
def wrapper(*args, **kwargs):
print("calling", func.__name__, args, kwargs)
return func(*args, **kwargs)
return wrapper
def area(width, height):
return width * height
logged_area = logged(area)
print(logged_area(3, height=4))
print(area(3, 4))
print(logged_area.__name__)
# ✅ Expected output:
# calling area (3,) {'height': 4}
# 12
# 12
# wrapperThe original area is untouched. The wrapper must hand back what the function returned, or every call gives None:
def logged(func):
def wrapper(*args, **kwargs):
print("calling", func.__name__)
func(*args, **kwargs)
return wrapper
def area(width, height):
return width * height
area = logged(area)
print(area(3, 4))
# ✅ Expected output:
# calling area
# NonePutting the wrapped function back under the original name, as area = logged(area) does, is common enough that Python has a shorthand for it: a @logged line above the def. Decorators & Advanced Features covers that shorthand and how to keep the original function's name.
Higher-order functions in the standard library
map() and filter(), from Lambda Functions, are higher-order functions too, and Comprehensions often do their jobs more readably. The functools module adds more: partial makes a new function with some arguments filled in, and reduce combines a list's items pairwise. For multiplying numbers together, math.prod is simpler still:
from functools import partial, reduce
import math
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5))
print(reduce(lambda a, b: a * b, [1, 2, 3, 4]))
print(math.prod([1, 2, 3, 4]))
# ✅ Expected output:
# 25
# 24
# 24functools: lru_cache, partial, reduce covers them in full.
Practice: a factory for pass marks
make_threshold(minimum) should return a test that checks whether a value reaches the minimum, so it can be passed to count_if. Fill the blanks: the name the inner function compares with, what the factory returns, and a pass mark of 80 for the last count. Use the hints under the code in order.
def make_threshold(minimum):
def check(value):
return value >= ___
return ___
def count_if(values, test):
total = 0
for value in values:
if test(value):
total += 1
return total
scores = [35, 50, 72, 18, 90]
passing = make_threshold(50)
print(passing(49), passing(50))
print(count_if(scores, passing))
print(count_if(scores, make_threshold(___)))
# 👉 replace ___ with minimum
# 👉 replace ___ with check
# 👉 replace ___ with 80
# ✅ Expected output:
# False True
# 3
# 1With return check() in the second blank, the factory calls the test straight away, without a value, and stops with a TypeError naming make_threshold.<locals>.check().
On your own: a username validator
Write make_validator(*rules). Each rule is a function that takes a text and returns True when the text passes. make_validator returns a function that takes a text and returns a list of the names of the rules it fails.
Write three rules, not_empty, short (8 characters or fewer) and no_spaces, build check_username from them, and print what it returns for "ada", "grace hopper" and "". A rule's __name__ gives its name. If you see TypeError: 'bool' object is not callable, a rule was called instead of passed.
# Write the three rules and make_validator(*rules) here.
# your code heredef not_empty(text):
return text != ""
def short(text):
return len(text) <= 8
def no_spaces(text):
return " " not in text
def make_validator(*rules):
def validate(text):
return [rule.__name__ for rule in rules if not rule(text)]
return validate
check_username = make_validator(not_empty, short, no_spaces)
print(check_username("ada"))
print(check_username("grace hopper"))
print(check_username(""))
# ✅ Expected output:
# []
# ['short', 'no_spaces']
# ['not_empty']
Practice quiz
def apply_twice(func, value): return func(func(value)), and def add_three(n): return n + 3. What does print(apply_twice(add_three, 10)) show?
- 13
- 10
- It stops with a TypeError
- 16
Answer: 16. add_three runs twice: 10 + 3 is 13, and 13 + 3 is 16.
With the same apply_twice and add_three, what does print(apply_twice(add_three(1), 10)) do?
- It stops with TypeError: 'int' object is not callable
- 16
- 17
- It stops with TypeError: add_three() missing 1 required positional argument: 'n'
Answer: It stops with TypeError: 'int' object is not callable. add_three(1) runs first and passes 4, a number, so apply_twice tries to call 4.
make_multiplier(factor) defines def multiply(n): return n * factor and ends with return multiply(). What does double = make_multiplier(2) do?
- Makes double a function that doubles
- Sets double to None
- It stops with TypeError: make_multiplier.<locals>.multiply() missing 1 required positional argument: 'n'
- It stops with a NameError
Answer: It stops with TypeError: make_multiplier.<locals>.multiply() missing 1 required positional argument: 'n'. The brackets call multiply straight away, with no n. Return the function itself: return multiply.
make_multiplier(factor) defines multiply inside it but has no return line. What does double = make_multiplier(2) followed by print(double(5)) do?
- It prints 10
- It stops with TypeError: 'NoneType' object is not callable
- It prints None
- It stops with NameError: name 'multiply' is not defined
Answer: It stops with TypeError: 'NoneType' object is not callable. Without return, make_multiplier gives None, so double is None, and None can't be called.
def compose(f, g) returns a function that works out f(g(x)). double doubles a number and add_one adds 1. What does print(compose(add_one, double)(3)) show?
- 7
- 8
- 6
- 4
Answer: 7. The inner function runs first: double(3) is 6, then add_one(6) is 7.
make_report(names) returns def report(): return ", ".join(names). A program runs team = ["Ada", "Grace"], show = make_report(team), team.append("Linus"), then print(show()). What prints?
- Ada, Grace
- It stops with an error
- Ada, Grace, Linus
- ['Ada', 'Grace', 'Linus']
Answer: Ada, Grace, Linus. report keeps the variable names, which refers to the list, and reads it when it runs, after Linus was added.
logged(func) returns def wrapper(*args): func(*args), with no return. A program runs area = logged(area), where area returns width * height, then print(area(3, 4)). What prints?
- 12
- It stops with a TypeError
- Nothing at all
- None
Answer: None. The wrapper calls the real area but drops its result, so it returns None.
def power(exponent): defines def raise_to(base): return base ** exponent, then runs exponent = exponent + 1, then returns raise_to. What does print(power(2)(5)) show?
- 25
- 125
- 10
- It stops with UnboundLocalError
Answer: 125. raise_to reads exponent when it runs, not when it's defined, and by then exponent is 3: 5 ** 3 is 125.
Continue this course
- Previous: Advanced Functions & Parameters Masterclass
- Next: Closures & Lexical Scope in Real Projects — Understand variable capture and build stateful function patterns
- Quick reference: Python cheat sheet
- From the blog: Python Decorators: A Practical Guide
Frequently asked questions
Can a factory return a lambda?
Yes: def make_multiplier(factor): return lambda n: n * factor works the same as returning a def'd function, so make_multiplier(2)(5) is 10. The function's __name__ is then <lambda>, which says less in an error message than a name like multiply.
How do I check that something can be called?
callable(thing) reports whether an object appears callable: functions, methods, classes and instances with a __call__ method can qualify. callable(len) is True and callable("len") is False. A True result doesn't promise that a particular set of arguments will work.
Why does printing a function show something like <function make_multiplier.<locals>.multiply at 0x7f…>?
That's the function's own description: its full name, here multiply made inside make_multiplier, and the memory address where it lives, which changes on every run. Print __name__ when you want the name.
Can map() take two lists?
Yes: given a function of two arguments, map() takes one item from each list per call, so list(map(pow, [2, 3, 4], [3, 2, 1])) is [8, 9, 4]. It stops at the shorter list, as zip() does.
Is a function factory the same as a class?
They overlap: both make things that carry their own data. A factory's function does one job; a class can hold several methods and data you can change. Closures & Lexical Scope in Real Projects compares the two.