A higher-order function is a function that:

  • takes another function as input

  • or returns a function

Higher-Order Function
├── takes function as argument
└── returns a function

example (function as argument)

def greet(func):
    func()
 
def say_hello():
    print("hello")
 
greet(say_hello)

output

hello

example (function returning function)

def outer():
    def inner():
        print("inside function")
    return inner
 
func = outer()
func()

output

inside function

real use example

def apply(func, value):
    return func(value)
 
def square(x):
    return x * x
 
print(apply(square, 5))

output

25

Note

  • Functions can be treated like variables
  • We can pass functions as arguments
  • Used in advanced concepts like map(), filter(), reduce()