Python Lambda Function-: A lambda function is a small anonymous function in python. lambda expressions are anonymous little functions that we can quickly define inline. Normally a small function needs to be passed to another function like the key function used by a list’s sort method. In such cases a large function is usually unnecessary and it would be awkward to have to define the function in a separate place from where it’s used.
lambda parameter1, parameter2,parameter3 . . .: expression
Importance of lambda function-:The main role of the lambda function is better described in the scenarios when we are using them anonymously inside another function. In the python the lambda function can be used as an argument to the higher order functions as arguments. Lambda functions are also used in the scenario when we needed. As like
x = lambda a : a + 10 print(x(15)) output of this 15
In another words we can say that the the power of lambda is better shown when we use them as an anonymous function inside another function.
def myfunc(n): return lambda a : a * n mytripler = myfunc(5) print(mytripler(12))
Output of this programme
Use of lambda function in python-: We use lambda functions when we require a nameless function for a short period of time.
In Python We use generally when an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter(), map() etc.
Example use with filter()-: The filter() 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 for which the function evaluates to True.
Here is an example use of filter() function to filter out only even numbers from a list.
lambdalist = [1, 3,5, 4,16, 6, 8, 11, 23, 12] lambdanewlist = list(filter(lambda x: (x%2 == 0) , lambdalist)) # Output: [4, 16,6 8, 12] print(lambdanewlist)
use with map() function -:The map() function in Python takes in a function and a list as like ..
lambdalist = [1, 3,5, 4,16, 6, 8, 11, 23, 12] lambdanewlist =list(map(lambda x: x * 2 ,lambdalist)) # Output: [2,6,10,8,32,12,16,22,46,24] print(lambdanewlist)