Higher Order Functions in Python (original) (raw)
Last Updated : 26 Feb, 2025
In Python, Higher Order Functions (HOFs) play an important role in functional programming and allow for writing more modular, reusable and readable code. A Higher-Order Function is a function that either:
- Takes another function as an argument
- Returns a function as a result
**Example:
Python `
def greet(func): # higher-order function return func("Hello")
def uppercase(text): # function to be passed return text.upper()
print(greet(uppercase))
`
**Explanation: greet(func) is a higher-order function as it takes another function as an argument. **uppercase(text) converts text to uppercase. Calling **greet(uppercase) passes “Hello” to uppercase, resulting in “HELLO”.
Examples of Higher Order Functions
**Example 1 : Passing a functions as an arguments
A function can be passed as an argument to another function, enabling dynamic behavior.
Python `
def apply(func, x): # higher order function return func(x)
def square(n): # function to be passed return n * n
print(apply(square, 5))
`
**Explanation:
- **apply(func, x) takes another function as an argument.
- **square(n) computes the square of **n.
- **apply(square, 5) executes square(5), resulting in 25.
**Example 2: Returning a function
A Higher-Order Function can return another function, allowing function generation dynamically.
Python `
higher order function returing a function
def fun(n): return lambda x: x * n
creating mutiliplier functions
double = fun(2) triple = fun(3)
print(double(5))
print(triple(5))
`
**Explanation:
- **fun(n) returns a lambda function that multiplies a number by n.
- **double and **triple are function instances that multiply by 2 and 3, respectively.
- Calling **double(5) results in 5 * 2 = 10 and **triple(5) results in 5 * 3 = 15.
Built in Higher Order Functions in Python
Python provides several built-in Higher Order Functions such as map(), filter() and sorted(), which simplify operations on iterable objects.
map()
A higher-order function that takes another function as an argument and applies it to each element in an iterable, enabling transformation without explicit loops.
Python `
Squaring each element in a list
a = [1, 2, 3, 4] res = list(map(lambda x: x ** 2,a)) print(res)
`
**Explanation: map(func, iterable) applies **func to each element in iterable and **lambda x: x ** 2 squares each number in the list.
filter()
A higher-order function that accepts a function to evaluate each element, returning only those that satisfy the given condition.
Python `
filtering even numbers
a = [1, 2, 3, 4, 5, 6] res = list(filter(lambda x: x % 2 == 0, a)) print(res)
`
**Explanation: filter(func, iterable) applies func to filter elements satisfying the condition and lambda x: x % 2 == 0 retains only even numbers.
sorted()
A higher-order function that sorts elements based on a provided key function, allowing custom sorting logic.
Python `
sorting words based on length
a = ["python", "java", "javascript"]
res = sorted(a, key=len) print(res)
`
Output
['java', 'python', 'javascript']
**Explanation: sorted(iterable, key=func) sorts based on **func applied to each element and **key=len sorts the strings by length.
Applications of Higher order functions
They are widely used in functional programming, closures, decorators, and callbacks to improve code modularity, reusability and abstraction. Let’s explore the applications of higher-order functions.
**Using closure
Closures allow functions to remember and use variables from their parent scope even after the parent function has finished running. This makes them essential for higher-order functions, enabling tasks like combining multiple functions , storing previous results for faster performance, breaking functions into smaller and efficiently handling arrays.
**Example:
Python `
def counter(start=0): # higher order function count = start
def increment(): # inner function
nonlocal count # retains access to 'count' even after counter() ends
count += 1
return count
return increment # returns the inner function
counter1 = counter(5) # closure retains count = 5
print(counter1())
print(counter1())
counter2 = counter(10) # new closure with count = 10 print(counter2())
`
**Explanation:
- **counter(start=0) returns increment, a closure that retains access to the enclosed count variable, allowing it to persist and update across calls.
- **increment() retains access to count, modifies it using nonlocal and increments it by 1 on each call. **counter() returns increment, allowing it to be called later.
- **counter(5) creates counter1 with count = 5. The first call increments it to 6 and the second call increases it to 7.
- **counter(10) initializes counter2 with count = 10. Calling **counter2() increments it to 11, independent of counter1.
Using decorator
Decorators extend or modify functions without changing their original code by wrapping them inside another function. They enhance higher-order functions by enabling tasks like caching results, controlling access (authentication), transforming inputs/outputs and tracking function calls.
**Example:
Python `
defining a decorator
def decor(func):
# wrapper function
def wrap():
print("Before function execution")
func() # calling the original function
print("After function execution")
return wrap
function to be decorated
def func():
print("Inside the function!")
applying the decorator
func = decor(func)
calling the decorated function
func()
`
Output
Before function execution Inside the function! After function execution
**Explanation:
- **decor(func) returns wrap, a closure that modifies func’s behavior.
- **wrap() prints messages before and after calling func().
- **func = decor(func) replaces **func with wrap, adding extra functionality.
- Calling func() now executes wrap(), printing messages and running func().