Open In App

Passing function as an argument in Python

Last Updated : 01 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Python, functions are first-class objects meaning they can be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, decorators and lambda expressions. By passing a function as an argument, we can modify a function’s behavior dynamically without altering its implementation. For Example:

def process(func, text):  # applies a function to text  
    return func(text)  

def uppercase(text):  # converts text to uppercase  
    return text.upper()  

print(process(uppercase, "hello"))

Output
HELLO

Explanation: process() applies a given function to text and uppercase() converts text to uppercase. Passing uppercase to process with “hello” results in “HELLO”.

Higher Order Functions

A higher-order function takes or returns another function, enabling reusable and efficient code. It supports functional programming with features like callbacks, decorators, and utilities such as map(), filter(), and reduce().

Example 1 : Basic function passing

# higher-order function
def fun(func, number):
    return func(number)

# function to double a number
def double(x):
    return x * 2

print(fun(double, 5))

Output
10

Explanation: fun() takes double() as an argument and applies it to 5, returning 10.

Example 2: Passing Built-in Functions

# function to apply an operation on a list
def fun(func, numbers):
    return [func(num) for num in numbers]

# using the built-in 'abs' function
a = [-1, -2, 3, -4]
print(fun(abs, a))

Output
[1, 2, 3, 4]

Explanation: abs() is passed to fun(), which applies it to each element in the list, converting negative numbers to positive.

Lambda Functions

A lambda function in Python is a small, anonymous function with a single expression, defined using lambda. It’s often used in higher-order functions for quick, one-time operations.

Example: Lambda Function as an Argument

# function that applies an operation to a number
def fun(func, number):
    return func(number)

# passing a lambda function
print(fun(lambda x: x ** 2, 5))

Output
25

Explanation: lambda x: x ** 2 is passed to fun(), which squares the input 5 to produce 25.

Wrapper Functions(Decorators)

A wrapper function (decorator) enhances another function’s behavior without modifying it. It takes a function as an argument and calls it within the wrapper.

Example 1 : Simple decorator

# simple decorator example
def decorator_fun(original_fun):
    def wrapper_fun():
        print("Hello, this is before function execution")
        original_fun()
        print("This is after function execution")
    return wrapper_fun

@decorator_fun
def display():
    print("This is inside the function !!")

# calling the decorated function
display()

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

Explanation: decorator_fun wraps the display() function, adding pre- and post-execution messages.

Example 2: Lambda Wrapper Function

def apply_lambda(func, value):
    return func(value)

square = lambda x: x ** 2
print("Square of 2 is:", apply_lambda(square, 2))

Output
Square of 2 is: 4

Explanation: apply_lambda() function applies the lambda function lambda x: x ** 2 to 2, returning 4.

Built-in Functions using function arguments

Python provides built-in functions that take other functions as arguments .

Example 1 : map()

a = [1, 2, 3, 4]
res = list(map(lambda x: x * 2, a))
print(res) 

Output
[2, 4, 6, 8]

Explanation: map() function applies lambda x: x * 2 to each element in a, doubling all values.

Example 2 : filter()

a = [1, 2, 3, 4, 5]
res = list(filter(lambda x: x % 2 == 0, a))
print(res)

Output
[2, 4]

Explanation: filter() selects even numbers from the list using lambda x: x % 2 == 0.

Example 3: reduce()

from functools import reduce
a = [1, 2, 3, 4]

res = reduce(lambda x, y: x + y, a)
print(res) 

Output
10

Explanation: reduce() function applies lambda x, y: x + y cumulatively to elements in a, summing them to 10.

Passing function as an argument in Python – FAQs

Can I Pass Functions as Arguments in Python?

Yes, in Python, functions are first-class objects. This means they can be passed as arguments to other functions, returned as values from other functions, and assigned to variables.

How Do You Pass a Function as an Argument?

To pass a function as an argument, simply refer to the function by its name without parentheses. Here’s a simple example:

def greet(name):
return f"Hello, {name}!"

def farewell(name):
return f"Goodbye, {name}!"

def process_user(callback, name):
print(callback(name))

# Passing functions as arguments
process_user(greet, "Alice")
process_user(farewell, "Bob")

This example demonstrates how a function can be passed as an argument (callback) to another function (process_user) and then executed within that function.

How Do You Pass a Function as an Argument in Python Decorator?

A decorator in Python is a function that takes another function and extends its behavior without explicitly modifying it. Here’s how to create a decorator that takes a function as an argument:

def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

# Calling the decorated function
say_hello()

In this example, say_hello() is passed to my_decorator() as the func argument. The wrapper function adds behavior before and after the call to say_hello().

How Do You Declare a Function Passing Argument?

To declare a function that can pass arguments, you define it using the def keyword followed by the function name and parentheses containing the arguments:

def multiply(x, y):
return x * y

# Using the function
result = multiply(5, 3)
print(result) # Output: 15

This function multiply takes two arguments, x and y, and returns their product.

How Many Types of Arguments Are There in Python?

Python supports several types of arguments:

  1. Positional Arguments: These are arguments that need to be passed in the correct positional order.
  2. Keyword Arguments: Arguments that are passed to functions using the name of the parameter, regardless of their position.
  3. Default Arguments: Parameters that assume a default value if a value is not provided in the function call.
  4. Variable-length Arguments:
    • Arbitrary Positional Arguments (*args): Allows you to pass a variable number of positional arguments.
    • Arbitrary Keyword Arguments (**kwargs): Allows for a variable number of keyword arguments.

Example of using various types of arguments:

def func_example(a, b=2, *args, **kwargs):
print(a, b)
print(args)
print(kwargs)

func_example(1, 3, 'extra', another=4)

This example highlights how Python accommodates flexibility in function arguments, making it a robust and versatile language for many programming paradigms.



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg