Lambda functions, also known as anonymous functions, are inline functions that do not have a name. They are used in Python when a function is needed for a short period of time, and is defined with the lambda keyword. Lambda functions can accept any number of arguments but can only have one expression.
The general syntax for a lambda function is: lambda arguments: expression
Lambda functions in filter(): The filter() function in Python takes in a function and a list as arguments. This function offers an elegant way to filter out all the elements of a sequence. For example, if we have a list of numbers and we want to filter out only the even numbers, we can use a lambda function within the filter() function:
Lambda functions in map(): The map() function in Python takes in a function and a list as arguments. The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item. For example, if we have a list and we want to square each item in the list, we can use a lambda function within the map() function:
Lambda functions in reduce(): The reduce() function in Python takes in a function and a list as arguments. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list. This is a part of functools module.
python
from functools import reduce
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
sum = reduce((lambda x, y: x + y), my_list)
print(sum)
Lambda for algebra: Lambda functions also shine when used in conjunction with algebraic tasks. For instance, suppose we have a function that multiplies two numbers:
python
double = lambda x: x * 2
print(double(5))
Lambda within user-defined functions: You can use a lambda function inside a user-defined function to create more complex functionalities:
python
def myfunc(n):
return lambda a : a * n
doubler = myfunc(2)
print(doubler(11))
Lambda functions with conditional statements: Lambda functions can also contain conditional statements for more complex logic:
python
x = lambda a : a+10 if a > 10 else a*10
print(x(12))
print(x(8))
In summary, lambda functions provide a concise way to create simple functions. They are useful in situations where you need a small, one-off function that you won't need to use elsewhere in your code.