Passing function as an argument in Python
Last Updated :
01 Mar, 2025
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:
Python
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"))
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
Python
# 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))
Explanation: fun() takes double() as an argument and applies it to 5, returning 10.
Example 2: Passing Built-in Functions
Python
# 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))
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
Python
# 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))
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
Python
# 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()
OutputHello, 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
Python
def apply_lambda(func, value):
return func(value)
square = lambda x: x ** 2
print("Square of 2 is:", apply_lambda(square, 2))
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()
Python
a = [1, 2, 3, 4]
res = list(map(lambda x: x * 2, a))
print(res)
Explanation: map() function applies lambda x: x * 2 to each element in a, doubling all values.
Example 2 : filter()
Python
a = [1, 2, 3, 4, 5]
res = list(filter(lambda x: x % 2 == 0, a))
print(res)
Explanation: filter() selects even numbers from the list using lambda x: x % 2 == 0.
Example 3: reduce()
Python
from functools import reduce
a = [1, 2, 3, 4]
res = reduce(lambda x, y: x + y, a)
print(res)
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:
- Positional Arguments: These are arguments that need to be passed in the correct positional order.
- Keyword Arguments: Arguments that are passed to functions using the name of the parameter, regardless of their position.
- Default Arguments: Parameters that assume a default value if a value is not provided in the function call.
- 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.
Similar Reads
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read
Python def Keyword
Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the âdefâ keyword. In Python def
6 min read
Difference between Method and Function in Python
Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method d
3 min read
First Class functions in Python
First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
2 min read
Assign Function to a Variable in Python
In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability. Example: [GFGTABS] Python # defining a function de
4 min read
User-Defined Functions
Python User Defined Functions
A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency. Example: [GFGTABS] Python # function de
6 min read
Python User Defined Functions
A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency. Example: [GFGTABS] Python # function de
6 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Defining a Python Function at Runtime
One amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. Itâs especially useful for things like metaprogramming, event-driven systems and running code dynamically
3 min read
Call a function by a String name - Python
In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
3 min read
Explicitly define datatype in a Python function
Unlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names. However, if we want to
4 min read
Built-in and Special Functions
Global and Local Variables
Parameters and Arguments
Python Function Parameters and Arguments
Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
3 min read
Keyword and Positional Argument in Python
Python provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call. Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Ke
4 min read
How to find the number of arguments in a Python function?
Finding the number of arguments in a Python function means checking how many inputs a function takes. For example, in def my_function(a, b, c=10): pass, the total number of arguments is 3. Some methods also count special arguments like *args and **kwargs, while others only count fixed ones. Using in
4 min read
Default arguments in Python
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argu
7 min read
Passing function as an argument in Python
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
6 min read
How to get list of parameters name from a function in Python?
The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis. For example, if a function fun(a,
4 min read
How to pass optional parameters to a function in Python?
In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Return Statements
How to pass optional parameters to a function in Python?
In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Returning Multiple Values in Python
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python Code # A Python program to return multiple # values from a
4 min read
Python None Keyword
None is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. C/C++ Code def check_return(): pass print(c
2 min read
Returning a function from a function - Python
In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior. Example: [GFGTABS] Python def fun1(name): def fun2(): return f"Hello, {name}!"
5 min read