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:

**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:

**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:

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:

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: