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.

Example

def apply_function(func, x):
   return func(x)
def square(x):
   return x ** 2
result = apply_function(square, 3)
print(result)

Output

9

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.

Example

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)

Output

7
12

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.

Example

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)

Output

[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.

Example

def square(x):
   return x * x
numbers = [1, 2, 3, 4, 5]
squares = list(map(square, numbers))
print(squares)

Output

[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.

Example

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

Output

[2, 4]

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.

Example

def get_length(word):
   return len(word)
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
sorted_words = sorted(words, key=get_length)
print(sorted_words)

Output

['date', 'apple', 'banana', 'cherry', '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.

Updated on: 02-May-2023

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements