Hi Python Developers, In this article, we are going to learn all about higher-order function in Python with the help of examples. As a Python developer, you must have knowledge of higher-order functions.
Python Higher Order Function
In Python Programming language, a Higher-order function accepts a function as a parameter and returns a function as an output. In nutshell, a higher-order function in Python that operates with another function is known as a higher-order function. Python too supports higher-order functions.
Properties of higher-order function
- A function is an instance of the Object type.
- A function can be stored inside a variable.
- A function can be passed as a parameter to another function.
- A function can return another function.
- A function can be stored inside a data structure like list, dictionary, etc.
Let’s see all the above Python higher-order function properties step by step.
Function as an Object
As you know that a function can be stored inside a variable, This assignment does not call the function, instead, it just creates the reference of that function.
def printName(text): print(text.upper()) # call the function printName("Python is a good language.") # assign function to variable func = printName # call func func("Python is best for machine learning.")
PYTHON IS A GOOD LANGUAGE. PYTHON IS BEST FOR MACHINE LEARNING.
Passing function as an argument to other function
As you know that in Python programming, functions are like an object, therefore this can be passed as an argument to another function. Let’s see an example.
def printName(func): print("Before function call!") func() print("After function call!") def text(): print("This is the higher order function.") # passing function as an argument printName(text)
Before function call! This is the higher order function. After function call!
A function can also return a function. let see how.
def printName(func): print("This is inside a function!") return func def text(): print("This is passing function.") # passing function as an argument result = printName(text) result()
This is inside a function! This is passing function.
So, In this article, we have seen all about higher-order functions in Python with their properties as well as examples. This is one of the most important concepts of Python programming and its aks by most of the interviewers during Python interviews.
So as a Python developer you must have knowledge of Python programming.
Python’s higher-order function is a function that accepts a function as a parameter and also returns a function as output.
Thanks for reading … 👏👏