Higher Order Functions in Python
A Higher Order Function (HOF) is a function that either:
- Takes another function as an argument, or
- Returns another function.
In Python, functions are treated as first-class objects. This means you can store them in variables, pass them to other functions, and return them from functions.
Syntax:
def higher_order(func):
# func is a function passed as argument
...
def outer():
def inner():
...
return inner
Example 1: Passing function as argument
def operate(func, number):
return func(number)
def square(x):
return x * x
def cube(x):
return x * x * x
print(operate(square, 4))
print(operate(cube, 3))
Output:
16
27
Explanation:
operateis a higher order function that takes another functionfuncand anumberas arguments.- When we call
operate(square, 4), it runssquare(4)which returns 16. - Similarly,
operate(cube, 3)callscube(3)which gives 27. - This shows how we can pass functions as arguments to other functions and reuse them for different tasks.
Example 2: Returning a function
def greet(msg):
def printer():
print("Welcome to", msg)
return printer
say_welcome = greet("ShikshaSanchar")
say_welcome()
Output:
Welcome to ShikshaSanchar
Explanation:
- The
greetfunction returns theprinterfunction. say_welcomenow holds thisprinterfunction and can be called later.- This shows how a function can return another function in Python.
- When we call
say_welcome(), it printsWelcome to ShikshaSanchar.
Why use Higher Order Functions?
- They make code more flexible and reusable.
- Very useful in tasks like filtering, mapping, decorators, etc.
- Allow powerful programming patterns by treating functions like normal data.
Summary:
- A higher order function can take a function as an argument or return a function.
- Python allows this because functions are first-class objects.
- Helps write clean, powerful, and reusable code.