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:

  • operate is a higher order function that takes another function func and a number as arguments.
  • When we call operate(square, 4), it runs square(4) which returns 16.
  • Similarly, operate(cube, 3) calls cube(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 greet function returns the printer function.
  • say_welcome now holds this printer function and can be called later.
  • This shows how a function can return another function in Python.
  • When we call say_welcome(), it prints Welcome 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.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar