Passing Function as an Argument in Python (original) (raw)
Function can be passed as an argument to another function. This helps create flexible and reusable programs where one function can perform different tasks using another function.
**Example: Here, a function is passed as an argument to another function to convert text into uppercase.
Python `
def process(func, text): return func(text)
def uppercase(text): return text.upper()
print(process(uppercase, "hello"))
`
**Explanation: uppercase() function is passed to process(). The process() function applies it to "hello" and returns "HELLO".
Higher Order Functions
A higher-order function is a function that takes another function as an argument or returns a function. It helps write reusable and cleaner code.
**Example 1: In this example, the double() function is passed to another function to double a number.
Python `
def fun(func, number): return func(number)
def double(x): return x * 2
print(fun(double, 5))
`
**Explanation: double() function multiplies the number by 2. It is passed to fun(), which applies it to 5 and returns 10.
**Example 2: Here, the built-in abs() function is passed to another function to convert negative numbers into positive numbers.
Python `
def fun(func, numbers): return [func(num) for num in numbers]
a = [-1, -2, 3, -4] print(fun(abs, a))
`
**Explanation: abs() function converts negative numbers into positive numbers. The fun() function applies it to every element in the list.
Lambda Functions
Lambda function is a small anonymous function written using the lambda keyword. It is commonly used when passing simple functions as arguments.
**Example: In this example, a lambda function is passed as an argument to square a number.
Python `
def fun(func, number): return func(number)
print(fun(lambda x: x ** 2, 5))
`
**Explanation: lambda function lambda x: x ** 2 squares the given number. It is passed to fun(), which applies it to 5 and returns 25.
Built-in Functions that Accept Functions
Python provides built-in functions like map(), filter() and reduce() that take functions as arguments to perform operations on data.
**Example 1: Here,map() applies a function to every element in the list.
Python `
a = [1, 2, 3, 4] res = list(map(lambda x: x * 2, a)) print(res)
`
**Explanation: map() applies the lambda function to each element in the list and doubles all the values.
**Example 2: In this example,filter() selects only even numbers from the list.
Python `
a = [1, 2, 3, 4, 5] res = list(filter(lambda x: x % 2 == 0, a)) print(res)
`
**Explanation: filter() checks each element using the lambda function and keeps only the even numbers.
**Example 3: Here,reduce() adds all elements of the list and returns a single result.
Python `
from functools import reduce a = [1, 2, 3, 4] res = reduce(lambda x, y: x + y, a) print(res)
`
**Explanation: reduce() repeatedly applies the lambda function to combine all elements of the list and returns their sum.