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 functionexample (function as argument)
def greet(func):
func()
def say_hello():
print("hello")
greet(say_hello)output
helloexample (function returning function)
def outer():
def inner():
print("inside function")
return inner
func = outer()
func()output
inside functionreal use example
def apply(func, value):
return func(value)
def square(x):
return x * x
print(apply(square, 5))output
25Note
- Functions can be treated like variables
- We can pass functions as arguments
- Used in advanced concepts like map(), filter(), reduce()