Syntax of Lambda Functionlambda arguments: expression Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required. Example of Lambda Function Here is an example of lambda function that doubles the input value.
# Program to demostrate use of lambda functions double = lambda x: x ** 2 print(double(5)) Output 25In the above program, lambda x: x ** 2 is the lambda function. Here x is the argument and x ** 2 is the expression that gets evaluated and returned. This function has no name. It returns a function object which is assigned to the identifier double. We can now call it as a normal function. The statement
How it works
double = lambda x: x ** 2 is nearly the same as def double(x): return x ** 2
Use of Lambda FunctionIn Python, lambda functions are used as an argument to a higher-order function i.e. 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 evaluats to True. Here is an example use of filter() function to filter out only even numbers from a list.
# Program to filter out evan numbers from a list using filter() and lambda functions numbers = [1, 9, 7, 6, 8, 5, 3, 4] even = list(filter(lambda x: (x%2 == 0) , numbers)) print(new_list) Output [4, 6, 8]
Example use with map()The map() function in Python takes a function and list. The function is applied with all the items in the list and a new list is returned which contains items returned by applying that function for each item. Here is an example use of map() function to double all the items in a list.
# Program to multiply item by 2 in a list using map() and lambda functions numbers = [1, 2, 3, 4, 5] doublenumber = list(map(lambda x: x * 2 , numbers)) print(doublenumber) Output [2, 4,6,8,10]