Python Higher Order Function
Python functions that can take other functions as arguments or return a function as a result are called higher-order functions.
Syntax
def high_order_function(function):
# perform some code here
return function
Example
def square(x):
return x * x
def cube(x):
return x * x * x
def high_order_function(func):
res = []
for i in range(1, 6):
res.append(func(i))
return res
print(high_order_function(square))
print(high_order_function(cube))
Output
[1, 4, 9, 16, 25]
[1, 8, 27, 64, 125]
Explanation
In the above example, we have defined two functions, square
and cube
, that calculate the square and cube of a given number respectively. We have also defined a higher-order function called high_order_function
that takes a function as an argument and returns a list of the calculated values for the specified range.
First, we pass the square
function as an argument to the high_order_function
. The high_order_function
calls the square
function for each value from 1 to 5 and stores the result in the res
array. Finally, it returns the res
array.
Similarly, we pass the cube
function as an argument to the high_order_function
and get the list of calculated values for 1
to 5
.
Use
Higher-order functions make it easier to write compact and expressive code. They are widely used in functional programming paradigms.
Some examples of higher-order functions in Python are map
, filter
, and reduce
.
Important Points
- Higher-order functions take one or more functions as input.
- Higher-order functions can return a function as output.
- Higher-order functions can manipulate functions like any other objects.
Summary
Python higher-order functions are functions that can take other functions as arguments or return a function as a result. They are used in functional programming paradigms to write compact and expressive code. Examples of higher-order functions in Python are map
, filter
, and reduce
.