Higher Order Functions
1. What Are Higher-Order Functions?
A Higher-Order Function (HOF) is a function that either:
- Takes one or more functions as arguments
- Returns a function as its result
They are a fundamental concept in functional programming and are supported in Python because functions are first-class citizens.
Examples
greet is passed to process_name as an argument.
process_name calls func(name) → greet("Abhijit").
2. Why Use Higher-Order Functions?
Promotes code reuse and modularity
Helps implement callbacks, decorators, and functional patterns
Clean and concise for data processing (e.g., using map, filter, etc.)
3. Common Built-in Higher-Order Functions in Python
4. Summary
Concept | Description |
---|---|
Higher-Order Function | Takes or returns another function |
map() |
Applies function to all items in iterable |
filter() |
Filters items based on a condition |
reduce() |
Reduces list to a single value |
Closures | Functions that remember the enclosing environment |
Decorators | Functions that modify other functions |
Practice Ideas
This custom function replicates Python’s
map
.It takes a function and an iterable, applies the function to each item, and collects the results in a list.
Explanation:
This decorator wraps the original function and measures how long it takes to run using time.time()
.
It is useful for performance profiling.
Explanation:
This chain of higher-order functions first filters even numbers from the list,
then squares them, and finally sums them using
reduce
.The result is the sum of squares of even numbers:
2² + 4² + 6² = 4 + 16 + 36 = 56
.