How to Create a Higher-Order Function in Python (Apply Twice)

This code defines a higher-order function that takes another function and a value, then applies the function twice to the value and returns the result.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

12 lines
Python 3.9+
def apply_twice(func, value):
    return func(func(value))

def add_ten(x):
    return x + 10

def square(x):
    return x ** 2

if __name__ == "__main__":
    print(apply_twice(add_ten, 5))
    print(apply_twice(square, 3))

Output

stdout
25
81

How it works

The apply_twice function is a higher-order function because it accepts a function (func) as an argument and invokes it. It calls func on the input value once, then calls func again on the result, effectively composing the function with itself. This pattern demonstrates functional programming concepts like function composition and passing functions as first-class objects. Using if __name__ == "__main__": ensures the test prints run only when the script is executed directly, not when imported.

Common mistakes

  • Forgetting to return the result of the inner call; ensure `return func(func(value))`.
  • Passing the function itself instead of calling it, e.g., `apply_twice(add_ten, 5)` is correct; `apply_twice(add_ten(), 5)` is wrong.
  • Assuming the inner function executes only once; it executes twice by design.

Variations

  1. Use a lambda: `apply_twice(lambda x: x * 2, 3)`
  2. Use `functools.reduce` to generalize for any number of applications.

Real-world use cases

  • Applying a transformation twice, like double-encoding a string or normalizing data twice for consistency.
  • Creating decorators that wrap a function multiple times for added behavior, such as logging and timing.
  • Implementing function composition in data pipelines where the same processing step must run twice on a value.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.