Python Lambda Functions
Python allows us to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions are declared by using lambda keyword. However, Lambda functions can accept any number of arguments, but they can return only one value in the form of expression. The anonymous function contains a small piece of code. It simulates inline functions of C and C++, but it is not exactly an inline function. The syntax to define an Anonymous function is given below.
Example 1
Output: sum = 30 Example 2Multiple arguments to Lambda function
Output: sum = 30 Why use lambda functions?The main role of the lambda function is better described in the scenarios when we use them anonymously inside another function. In 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 where we need a Consider the following example. Example 1
Output: Enter the number?10 10 X 1 = 10 10 X 2 = 20 10 X 3 = 30 10 X 4 = 40 10 X 5 = 50 10 X 6 = 60 10 X 7 = 70 10 X 8 = 80 10 X 9 = 90 10 X 10 = 100 Example 2Use of lambda function with filter
Output: [3, 123] Example 3Use of lambda function with map
Output: [3, 6, 9, 12, 30, 66, 369] |