What is the lambda function in python? Explain with an example
In python, the Anonymous function (A function without a name) is called lambda function. Lambda function can accept multiple arguments with only one expression. It does not include any statement.
Syntaxlambda parameters: expression
subtract_number = lambda a, b: a - b print("Result:",subtract_number(5, 2))
Output: ('Result:', 3)
Explanation: Here an anonymous function is defined with keyword lambda. Passing two arguments a & b with one expression a - b
Normal function in python is defined using keyword def but anonymous function is defined by using lambda keyword. lambda functions help to reduce lines of code as we don’t need to define normal functions using the def keyword for one line expression code.
Lambda function are mostly used with built-in functions such as filter, map & reduce function
Let’s go through most asked reverent queries with explanations
1. Can we create multi-lines lambda functions?
No. Lambda function can receive multiple arguments but only one expression. Better go with normal function created by using keyword def in case required multiple lines of code.
2. How to use lambda function within map in python?
As explained above lambda functions are mostly used with built-in functions map. Let’s first see the below map example used with normal python function.
def add5(x): return x + 5 print("Each Number + 5:",map(add5, [1, 2, 3, 4]))
('Each Number + 5:', [6, 7, 8, 9])
Explanation: Here map function in combination with normal add5 function is performing to add 5 to each of the numbers in the given list. Also here function add5 contains a single expression therefore we can rewrite same code using lambda function.
print("Each Number + 5:",map(lambda x: x+5, [1, 2, 3, 4]))
Explanation: We can see the lambda function inside the map doing the same operations as done by normal function in Example 1 and clubbed into one line of code using lambda in combination with map function.