In Python, the function which is defined without a name is known as anonymous function.
Here normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
Lambda functions are used along with built-in functions like filter(), map() etc.
The general form(Syntax) is:
lambda 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.
# lambda function result = lambda y: y * 5 print(result(10))
Here lambda y: y * 2 is the lambda function. Here y is the argument and y * 2 is the expression that is evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier result.
result = lambda y: y * 5
is nearly the same as
return y * 5
In Python, filter() function takes a list as arguments inside a function.
The filter() function is called with all the items in the list and lambda function will be passed inside the filter().
# Program to filter out only the odd items from a list x = [1, 2, 3,4,5,6,7,8,9] y = list(filter(lambda p: (p%2 != 0) , x)) print(y)
[1, 3, 5, 7, 9]
In Python, map() function takes in a function and a list.
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.
# Program to tripple each item in a list using map() numbers = [1,2,3,4] new_numbers = list(map(lambda y: y * 3 , numbers)) print(new_numbers)
[3, 6, 9, 12]
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc