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.
Python code
12 linesdef 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
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
- Use a lambda: `apply_twice(lambda x: x * 2, 3)`
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.