- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How to pass Python function as a function argument?
In Python, you can pass a function as an argument to another function. This is known as a higher-order function.
In other words, a function is called a higher-order function if it contains other functions as parameters or returns functions. Python supports the usage of higher-order functions as it is a very versatile programming language.
Few examples of higher-order functions in Python are map(), filter(), sorted(), and reduce().
For example the function map() applies a function to all the items in an input list and returns a new list containing all the function call results and similarly other higher order functions have specific use cases.
In the example given below, the apply_function function takes two arguments: a function func and a value x. It applies the function func to the value x and returns the result. The square function is defined separately, which takes a number and returns its square.
def apply_function(func, x): return func(x) def square(x): return x ** 2 result = apply_function(square, 3) print(result)
Passing functions as arguments can be useful for writing more flexible and reusable code. You can pass in different functions to achieve different behaviors, without having to write separate functions for each behavior.
Let us consider another example that demonstrates how to pass a function as an argument to another function in Python:
In this example, we have three functions: add, multiply, and apply operation. The add and multiply functions take two numbers as arguments and return their sum and product, respectively. The apply operation function takes a function func and two numbers x and y as arguments. It applies the function func to the two numbers x and y and returns the result.
We call the apply_operation function twice: once with the add function and the numbers 3 and 4, and once with the multiply function and the same numbers. The first call applies the add function to the numbers 3 and 4, which returns 7. The second call applies the multiply function to the same numbers, which returns 12.
In both calls, we pass the add and multiply functions as the first argument to the apply_operation function. This allows us to use the same apply_operation function for different operations, without having to write separate functions for each operation.
def add(x, y): return x + y def multiply(x, y): return x * y def apply_operation(func, x, y): return func(x, y) result = apply_operation(add, 3, 4) print(result) result = apply_operation(multiply, 3, 4) print(result)
Passing functions as arguments can make your code more flexible and reusable. You can define a set of functions that perform different operations and pass them as arguments to a higher-order function that applies them to input data. This allows you to write more generic code that can be adapted to different scenarios by simply changing the functions that are passed as arguments.
Here's yet another example that demonstrates how to pass a function as an argument to another function in Python:
In this example, we have two functions: filter_list and is_even. The filter_list function takes a function func and a list lst as arguments. It applies the function func to each item in the list lst and returns a new list that contains only the items for which the function returns True. The is_even function takes a number as an argument and returns True if the number is even and False otherwise.
We define a list of numbers and then call the filter_list function twice: once with the is_even function and the list of numbers, and once with a new function is_positive that returns True if a number is positive and False otherwise. The first call returns a new list that contains only the even numbers in the original list, while the second call returns a new list that contains all the numbers in the original list (since they are all positive).
By passing functions as arguments to the filter_list function, we can use the same function to filter different lists based on different criteria. This allows us to write more generic and reusable code.
def filter_list(func, lst): result =  for item in lst: if func(item): result.append(item) return result def is_even(num): return num % 2 == 0 def is_positive(num): return num > 0 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = filter_list(is_even, numbers) print(even_numbers) positive_numbers = filter_list(is_positive, numbers) print(positive_numbers)
[2, 4, 6, 8, 10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In Python, functions are first-class objects, which means that you can pass them as arguments to other functions. This feature allows you to write higher-order functions that take other functions as arguments and use them to customize their behavior.
Passing a function as an argument to map()
The built-in map() function applies a function to each element of an iterable and returns a new iterable with the results. You can pass any function as the first argument to map(), as long as it takes one argument.
In this example, we define a function called square that takes one argument and returns its square. We then define a list of numbers and use map() to apply the square function to each number. The resulting squares list contains the squares of the original numbers.
def square(x): return x * x numbers = [1, 2, 3, 4, 5] squares = list(map(square, numbers)) print(squares)
[1, 4, 9, 16, 25]
Passing a lambda function as an argument to filter()
The built-in filter() function applies a function to each element of an iterable and returns a new iterable with the elements that pass a certain condition. You can pass any function as the first argument to filter(), as long as it returns a boolean value.
In this example, we define a list of numbers and use filter() to apply a lambda function that checks if each number is even. The resulting evens list contains only the even numbers from the original list.
numbers = [1, 2, 3, 4, 5] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens)
Passing a function as an argument to sorted()
The built-in sorted() function sorts a list of elements using a comparison function. You can pass any function as the key argument to sorted(), as long as it takes one argument and returns a comparable value.
In this example, we define a function called get_length that takes a word and returns its length. We then define a list of words and use sorted() to sort them by length. The resulting sorted_words list contains the words sorted in ascending order by length.
def get_length(word): return len(word) words = ['apple', 'banana', 'cherry', 'date', 'elderberry'] sorted_words = sorted(words, key=get_length) print(sorted_words)
['date', 'apple', 'cherry', 'banana', 'elderberry']
Passing functions as arguments is a powerful feature of Python that allows you to write higher-order functions that can be customized with different functions. This can make your code more flexible and reusable, and can save you a lot of time and effort. By using higher-order functions and functional programming techniques, you can write cleaner, more concise, and more maintainable code.
- Related Articles
- How to pass Python function as a function argument?
- How to pass a dictionary as argument in Python function?
- Java Program to Pass ArrayList as the function argument
- How to pass entire array as an argument to a function in C language?
- How to pass entire structure as an argument to function in C language?
- How to pass an entire structure as an argument to function in C?
- How to pass the address of structure as an argument to function in C?
- How to pass individual elements in an array as argument to function in C language?
- How to pass the address of structure as an argument to function in C language?
- How to pass a json object as a parameter to a python function?
- Python Program to pass the tuple as function arguments
- How to pass a function as a parameter in Java
- How to call a function with argument list in Python?
- How to pass optional parameters to a function in Python?