Open In App

Higher Order Functions in Python

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A function is called

Higher Order Function

if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another function are known as Higher order Functions. It is worth knowing that this higher order function is applicable for functions and methods as well that takes functions as a parameter or returns a function as a result. Python too supports the concepts of higher order functions.

Properties of higher-order functions:

  • A function is an instance of the Object type.
  • You can store the function in a variable.
  • You can pass the function as a parameter to another function.
  • You can return the function from a function.
  • You can store them in data structures such as hash tables, lists, …

Functions as objects

In Python, a function can be assigned to a variable. This assignment does not call the function, instead a reference to that function is created. Consider the below example, for better understanding.

Example:

Python3 1==
# Python program to illustrate functions 
# can be treated as objects 
def shout(text): 
    return text.upper() 
  
print(shout('Hello')) 
  
# Assigning function to a variable
yell = shout 
  
print(yell('Hello'))

Output:

HELLO
HELLO

In the above example, a function object referenced by shout and creates a second name pointing to it, yell.

Passing Function as an argument to other function

Functions are like objects in Python, therefore, they can be passed as argument to other functions. Consider the below example, where we have created a function greet which takes a function as an argument.

Example:

Python3 1==
# Python program to illustrate functions 
# can be passed as arguments to other functions 
def shout(text): 
    return text.upper() 
  
def whisper(text): 
    return text.lower() 
  
def greet(func): 
    # storing the function in a variable 
    greeting = func("Hi, I am created by a function \
    passed as an argument.") 
    print(greeting)  
  
greet(shout) 
greet(whisper)

Output:

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

Returning function

As functions are objects, we can also return a function from another function. In the below example, the create_adder function returns adder function.

Example:

Python3 1==
# Python program to illustrate functions 
# Functions can return another function 
  
def create_adder(x): 
    def adder(y): 
        return x + y 
  
    return adder 
  
add_15 = create_adder(15) 
  
print(add_15(10))

Output:

25

Decorators

Decorators are the most common use of higher-order functions in Python. It allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.

Syntax:

@gfg_decorator
def hello_decorator():
.
.
.

The above code is equivalent to –


def hello_decorator():
.
.
.

hello_decorator = gfg_decorator(hello_decorator)

In the above code,

gfg_decorator

is a callable function, will add some code on the top of some another callable function,

hello_decorator

function and return the wrapper function.

Example:

Python3 1==
# defining a decorator 
def hello_decorator(func): 
  
    # inner1 is a Wrapper function in  
    # which the argument is called 
      
    # inner function can access the outer local 
    # functions like in this case "func" 
    def inner1(): 
        print("Hello, this is before function execution") 
  
        # calling the actual function now 
        # inside the wrapper function. 
        func() 
  
        print("This is after function execution") 
          
    return inner1 
  
  
# defining a function, to be called inside wrapper 
def function_to_be_used(): 
    print("This is inside the function !!") 
  
  
# passing 'function_to_be_used' inside the 
# decorator to control its behavior 
function_to_be_used = hello_decorator(function_to_be_used) 
  
  
# calling the function 
function_to_be_used() 

Output:

Hello, this is before function execution
This is inside the function !!
This is after function execution

Note:

For more information, refer to

Decorators in Python

Higher Order Functions in Python – FAQs

Is lambda a higher-order function in Python?

No, lambda functions are not higher-order functions. They are used to create anonymous functions. However, they can be used as arguments in higher-order functions.

Why is lambda faster in Python?

lambda functions are slightly faster due to their simple, one-line syntax and lack of a formal function definition overhead. However, this performance gain is usually marginal.

What is the highest function in Python?

The concept of functions as first-class objects means there is no single “highest” function. Functions can be passed around, returned from other functions, and assigned to variables.

What is the difference between a regular function and a higher-order function?

A regular function performs operations, while a higher-order function can accept other functions as arguments or return them, enabling functional programming techniques.

How do higher-order functions relate to functional programming?

Higher-order functions are fundamental in functional programming. They allow functions to be used as arguments or return values, enabling more abstract and functional code.



Similar Reads

Higher-Lower Game with Python
In this article, we will be looking at the way to design a game in which the user has to guess which has a higher number of followers and it displays the scores. Game Play:The name of some Instagram accounts will be displayed, you have to guess which has a higher number of followers by typing in the name of that account. Make sure you type the name
8 min read
Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
Some of the mathematical functions are discussed in below set 1 and set 2 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Trigonometric and angular functions are discussed in this article. 1. sin() :- This function returns the sine of value passed as argument. T
3 min read
Mathematical Functions in Python | Set 4 (Special Functions and Constants)
Some of the mathematical functions are discussed in below set 1, set 2 and set 3 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) Special Functions and constants are discussed in this
2 min read
Python MySQL - Order By Clause
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause OrderBy is used to arrange the result set in either ascending or descendi
2 min read
Python | Check order of character in string using OrderedDict( )
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All 'e' in the input string are before all 'r'.Input:
3 min read
Python code to print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1 time), k(1 time) and s(1 time). Hence the lexicogr
2 min read
Sort the words in lexicographical order in Python
Given a strings, we need to sort the words in lexicographical order (dictionary order). Examples : Input : "hello python program how are you" Output : are hello how program python you Input : "Coders loves the algorithms" Output : Coders algorithms loves the Note: The words which have first letter is capital letter they will print according alphabe
2 min read
Python | Sort Tuples in Increasing Order by any key
Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] E
3 min read
Python | Sort words of sentence in ascending order
Given a sentence, sort it alphabetically in ascending order. Examples: Input : to learn programming refer geeksforgeeksOutput : geeksforgeeks learn programming refer to Input : geeks for geeksOutput : for geeks geeks Approach 1 : We will use the built-in library function to sort the words of the sentence in ascending order. Prerequisites: split() s
2 min read
Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers, the task is to sort all even-placed numbers in increasing and odd-place numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered as even because of its index 0. Examples: Input: a
2 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | All Permutations of a string in lexicographical order without using recursion
Write a python program to print all the permutations of a string in lexicographical order. Examples: Input : python Output : hnopty hnopyt hnotpy hnotyp hnoypt ...... ytpnho ytpnoh ytpohn ytponh Input : xyz Output : xyz xzy yxz yzx zxy zyx Method 1: Using the default library itertools function permutations. permutations function will create all the
2 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
SymPy | Permutation.order() in Python
Permutation.order() : order() is a sympy Python library function that calculates the order of a permutation. When the permutation is raised to the power of its order, then, in that case, the order equals the identity permutation. Syntax : sympy.combinatorics.permutations.Permutation.order() Return : order of the permutation Code #1 : order() Exampl
1 min read
Python | Relative sorted order in Matrix
Sometimes, while working with Python Matrix, we can have data arranged randomly and we can have a requirement in which we need to get the element position in sorted order of Matrix. Let's discuss a certain way in which this task can be performed. Method : Using list comprehension + enumerate() + sort() + lambda The solution to problem can be achiev
4 min read
Python MariaDB - Order By Clause using PyMySQL
A MySQL client library is employed when we have to use MySQL with other programming languages. The work of PyMySQL is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause The OrderBy is used to arrange the result set in either ascending or d
2 min read
How to compare JSON objects regardless of order in Python?
JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primaril
2 min read
How to reverse column order in a matrix with Python?
In this article, we will see how to reverse the column order of a matrix in Python. Examples: Input: arr = [[10,20,30], [40,50,60], [70,80,90]] Output: 30 20 10 60 50 40 90 80 70 Input: arr = [[15,30], [45,60], [75,90], [105,120]] Output: 30 15 60 45 90 75 120 105 Matrices are created in python by using nested lists/arrays. However, a more efficien
2 min read
Python SQLite - ORDER BY Clause
In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data in descending order.ASC to sort in ascending order.
3 min read
Python PostgreSQL - Order By
In this article, we will discuss how to use order by clause in PostgreSQL using python. The Order By clause is used to sort the records of a table returned by the SELECT clause in ascending order by default, yet asc keyword can be used. If we want to sort the records in descending order then we have to write desc word. Syntax : SELECT column1, colu
3 min read
Integrate a Chebyshev series and set the order of integration using NumPy in Python
In this article, we will discuss how to integrate the Chebyshev series and set the order of integration in Python and NumPy. chebyshev.chebint method Chebyshev polynomials are significant in approximation theory because the Chebyshev nodes are used as matching points for optimizing polynomial interpolation. To perform Chebyshev Integration, NumPy p
4 min read
Evaluate the lowest cost contraction order for an einsum expression in Python
In this article, we will see how to Evaluate the lower cost contraction for an einsum expression in Python. np.einsum_path method To obtain the lowest cost contraction order for an einsum expression in Python, use the numpy.einsum path() function. The Einstein summation convention can be used to represent several common multi-dimensional linear alg
2 min read
How to use numpy.argsort in Descending order in Python
The numpy.argsort() function is used to conduct an indirect sort along the provided axis using the kind keyword-specified algorithm. It returns an array of indices of the same shape as arr, which would be used to sort the array. It refers to value indices ordered in ascending order. In this article, we will see how we can use NumPy argsort for sort
4 min read
Change the order of a Pandas DataFrame columns in Python
When expanding Pandas dataframes with extra columns, the structure may become unwieldy, and the column arrangement might lose its coherence. To enhance the readability of your dataframes, it's common to reorder the columns, placing them in a more logical sequence. In this article, we are going to see how to change the order of dataframe columns in
5 min read
heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] This problem h
2 min read
How To Fix "Typeerror: Cannot Create A Consistent Method Resolution Order (Mro)" In Python
When working with Python, it is usual to encounter mistakes. One such issue, "TypeError: Cannot create a consistent method resolution order (MRO)," might be very aggravating. This issue usually occurs when there is a dispute in the inheritance structure of classes. In this article, we will explore the causes of this error and provide effective solu
3 min read
Method resolution order in Python Inheritance
Method Resolution Order : Method Resolution Order(MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass. In python, method resolution order define
7 min read
Reorder Columns in a Specific Order Using Python Polars
Polars is a powerful DataFrame library in Rust and Python that is known for its speed and efficiency. It's designed to handle large datasets with ease, making it an excellent choice for data analysis and manipulation. One common task in data manipulation is reordering the columns of a data frame. This article will guide you through three different
4 min read
Article Tags :
Practice Tags :