What is Python Anonymous or Lambda Function?
Python Anonymous/Lambda Function
What are lambda functions in Python?
In Python, an anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword in Python, anonymous functions are de Hence, anonymous functions are also called lambda functions.
Best Python Training Institute in Gurgaon
How to use lambda Functions in Python?
A lambda function in python has the following syntax. #### Syntax of Lambda Function in python
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.
Example of Lambda Function in python
[1]: #program to show the use of lamba function
double = lambda x: x * 2
print (double(5)
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 This function has no name. It returns a function object which is assigned to the identifier do
[2]: double = lambda x: x * 2
is nearly the same as:
[3]: def double(x):
return x * 2
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 generally use it as an argument to a higher-order function (a function that take
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 contain Here is an example use of filter() function to filter out only even numbers from a list.
[5]: # program to filter out only the even item from a list
my list = [1, 5, 4, 6, ,8, 11, 3, 12]
new list = list(filter (lambda x: (x 2 /== 0), my list ))
print (new list)
[4, 6, 8, 12]
#### Example use with map()
The map() function in Python 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 contain Here is an example use of map() function to double all the items in a list.
[6]: Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list)) print(new_list)
[2, 10, 8, 12, 16, 22, 6, 24]
Use of lambda() with reduce()
The reduce() function in Python takes in a function and a list as argument. The function is ca
[7]: # Python code to
illustrate # reduce() with lambda()
# to
get sum of a list
from functools import reduce li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li) print
(sum)
193
Get More Information About PythonTraining and Certification Course Visit Here.
Comments
Post a Comment