Python: How to pass a function as an argument?

Python Function As An Argument

Hello folks! In this tutorial, we are going to discuss the different ways to pass a function as an argument in Python.


What are Functions in Python?

In Python programming, a function plays a very crucial role. We have a very wide and rich collection of different types of functions in Python. Functions in Python provides modularity feature. It means using functions we can divide a single large block of Python code into smaller blocks where each block has to perform a specific task. We can either use predefined functions or define our own functions. The functions which are defined inside a specific class we call them methods in Python.

Functions as first-class objects

First-class objects are those objects which are treated uniformly throughout the program. It means the first-class objects can be stored in a variable, passed as an argument to a function, or used in control statements. Python supports the concept of first-class objects and treats functions as first-class objects. It is because of this reason, we can pass functions as arguments to other functions in Python.

How to pass a function as an argument in Python?

In Python, we can pass different types of functions as an argument to another function in the following ways. Let’s discuss them one by one.

1. User-defined function

In Python, just like a normal variable, we can pass a user-defined function as an argument to another function. A function that accepts another function as its parameter is called a Higher-order function. Let’s see how we can implement this through Python code.

# Define higher order function
def fun(foo):
    result = foo('Welcome To AskPython!!')
    return result

# Define function-1
def fun1(str):
    return str.lower()

# Define function-2
def fun2(str):
    return str.upper()

# Pass funtion-1 as an argument
# to fun() function
str1 = fun(fun1)
print(str1)

# Pass funtion-2 as an argument
# to fun() function
str2 = fun(fun2)
print(str2)

Output:

welcome to askpython!! 
WELCOME TO ASKPYTHON!!

2. Class method

Like user-defined functions, we can also pass class methods as an argument. Let’s define a class in Python with two methods and create an object of this class to call those methods. Let’s see the Python code to implement this.

# Define a Python class
class demo_class:
    # Define method-1
    def method1(self):
        print("Method-1 Running")
        return "AskPython!!"
    # Define method-2
    def method2(self, foo):
        print("Method-2 Running")
        result = foo()
        return result

# Create a demo_class object
# using the class constructor
obj = demo_class()

# Pass method-1 as an argument to method-2
str = obj.method2(obj.method1)
print(str)

Output:

Method-2 Running 
Method-1 Running 
AskPython!!

3. Lambda function

In Python, lambda functions are the function objects returned on evaluation of the lambda expressions. Like user-defined functions and class methods, we can also pass a lambda function as an argument to another function. Let’s see the Python code to implement this.

# Create a Python list
ls = [1, 2, 3, 4, 5]
print('This is the given list:')
print(ls)

# Pass lambda function 
# to map() function to claculate
# the square of each list element
iter_obj = map((lambda n: n**2), ls)

# Construct the list again with
# square of the elements of the given list
ls = list(iter_obj)
print('This is the final list:')
print(ls)

Output:

This is the given list: 
[1, 2, 3, 4, 5] 
This is the final list: 
[1, 4, 9, 16, 25]

4. Operator function

In Python, we have the operator module which contains predefined functions. These functions allow us to perform mathematical, relational, logical, or bitwise operations on a given list of arguments. Like user-defined and lambda functions we can also pass an operator function as an argument to another function. Here we will be using operator.mul() function from the operator module and pass it to the reduce() function which is defined in the functools module along with a Python list. This will calculate and return the product of the passed list elements. Let’s implement this through Python code.

# Importing Python functools module which contains the reduce() function
import functools
 
# Importing Python operator module which contains the mul() function
import operator
 
# Defining a Python list
ls = [1, 3, 5, 7, 9, 11]
print("Given Python list:")
print(ls)

# Pass the mul() function as an argument 
# to the reduce() function along with the list
ls_product = functools.reduce(operator.mul, ls)
  
# Printing the results
print("Product of the given Python list: ", ls_product)

Output:

Given Python list: 
[1, 3, 5, 7, 9, 11] 
Product of the given Python list:  10395

5. Built-in function

In Python, we have so many standard built-in functions like list(), tuple(), dict(), str(), etc. Like the user-defined functions, we can also pass the built-in function as an argument to another function in Python. Here we will pass the str() function to the map() function along with a Python tuple of strings and numbers. This will return an iterator object which we will to the str.join() function to convert the given tuple to Python string. Let’s write the Python code to implement this.

# Create a Python tuple
tup = ('Linux', 'Ubuntu', 20.04)
print("Given Python tuple:")
print(tup)

# Pass the str() function
# to the map() function
iter_obj = map(str, tup)

# Construct the string from 
# the returned iterator object
# of the given tuple
str1 = "-".join(iter_obj)

# Print the result
print("Generated Python string from tuple:")
print(str1)

Output:

Given Python tuple: 
('Linux', 'Ubuntu', 20.04) 
Generated Python string from tuple: 
Linux-Ubuntu-20.0

Conclusion

In this tutorial, we have learned the following things:

  • What is are first-class objects?
  • How to pass user-defined function as an argument?
  • How to pass class methods as an argument?
  • How to pass lambda function as an argument?
  • How to pass operator function as an argument?
  • How to pass built-in function as an argument?

Hope you have understood all the concepts discussed above and ready to learn and explore more about the functions in Python. Stay tuned with us!