Learning Objectives
-
Lambda function
-
Map and Lambda
-
Filter and Lambda
Earlier Function
- Earlier, we used the 'def' keyword to define a function
- And in the body of the function, we added the logic of the function
- A lambda function is an anonymous function. Now, what is an anonymous function? An anonymous function is a function that is defined without any name.
- For example, we defined a function in the earlier topic that can be called whenever required with a name 'even()', the map function can be called using the name' map()' while lambda functions cannot be called whenever required. We define the lambda function whenever needed.
- The lambda function can take any number of arguments but only has one expression. Let's understand through examples.
Syntax
1
lambda arguments: expression
For example, we had defined a function to calculate the square of the number. We used the map function to get the list of squares of the numbers in a list.
As mentioned earlier, the lambda function can take any number of arguments. Let's calculate the element-wise sum of two lists.
Try It Yourself
Can you filter out the even numbers from the list, l1 = [5, 7, 8, 10, 11, 13, 15, 16, 17, 19, 20] using lambda function? Think ???? and write a Python program to filter out the even numbers before continuing.
The above code can also be written as: