How to Pass Function as Argument in Python?

share link

by Abdul Rawoof A R dot icon Updated: Feb 1, 2023

technology logo
technology logo

Guide Kit Guide Kit  

In Python, functions are first-class citizens, meaning they can be treated like any other data type, such as integers or strings. This means you can pass a function as an argument to another function, just like you would pass any other value. 


A value or variable provided to a function when it is called is referred to as an argument. The function uses these arguments as inputs to perform a specific task or calculation and may return a result or perform a specific action. In Python, the get() method is used to access the value of a key in a dictionary. 


There are a few ways to pass a function as an argument in Python: 

  • Using the name of the function. 
  • Using a lambda function. 
  • Using the “functools.partial” function to create a new function with some pre-filled arguments. 
  • functools.partial: This is a function in the Python standard library that allows you to create a new function with some pre-filled arguments. It returns a new function with the given arguments partially applied. 


You may have a look at the code given below for passing a function as an argument in Python. 

Fig : Preview of the output that you will get on running this code from your IDE.

Code

Instructions

Follow the steps carefully to get the output easily.

  1. Install python on your IDE(Any of your favorite IDE).
  2. Copy the snippet using the 'copy' and paste it in your IDE.
  3. Run the file to generate the output.


I hope you found this useful.

I found this code snippet by searching for 'Passing function as an argument in python'in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in PyCharm 2021.3.
  2. The solution is tested on Python 3.9.7.


Using this solution, we are able to passing function as an argument in python with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to passing function as an argument in python.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.