In this article, we will discuss lambda function definition and usages in Python. Lambda functions are also known as anonymous function or lambda expression.
Lambda function definition
A lambda function/expression is a notation used in the lambda calculus.
A normal function is , where x is a variable
f(x) = M
but a lambda function as shown below
λx.M
Where M is an expression uses x.
The python syntax for lambda function is
lambda x: M
Simple example of Lambda function
Let’s see a simple example of lambda function in Python. Below lambda function will add 1 to the argument.
increment = lambda x: x + 1
print(increment (9))
Output
10
In the above example, lambda x : x + 1 is the lambda function , it follows lambda function syntax (lambda x: M) and we can see M is x+1.
The lambda function lambda x : x + 1 is same as normal function as shown below :
def increment(x):
return x+1
When to use Lambda functions?
Lambda functions are nameless functions it can be used for a short period (sorting, filtering, etc). We can use the lambda function with higher-order functions. Higher-order functions simply mean a function that takes another function as argument.
The map, filter, reduce functions can use lambda functions. Let’s look into some examples.
Example usage with map function
Suppose we have a list of numbers and we want to double every element in the list.
numbers = [10,20,30,40,50]
double_num = map(lambda x : x*2 , numbers)
print(list(double_num))
From the above example, we can see lambda function lambda x: x*2 is used as the first argument to map function and every list element gets multiplied by 2.
Output
[20, 40, 60, 80, 100]
Example usage with filter function
Suppose we have a list of numbers and when we want to filter even numbers from the list we can use filter function with lambda expression.
numbers = [1,20,3,46,35,50,4,27]
even_nums = filter (lambda x : x%2 ==0 , numbers)
print(list(even_nums))
Here we have passed a lambda function(lambda x : x%2 ==0) to filter the even numbers.
Output
[20, 46, 50, 4]
Example usage with reduce function
Suppose we have a list of numbers, and when we want to find the sum of all elements we can use reduce function.
from functools import reduce
numbers = [10,20,30,40]
num_sum = reduce(lambda a,b : a + b , numbers )
print(f"Sum is : {num_sum}")
Output
Sum is : 100
From the above example , we can see the lambda expression lambda a,b : a + b is passed as an argument to reduce function.
Conclusion
In conclusion, we have discussed definition and usages of lambda functions in Python.