What is the lambda function in python? Explain with an example
In Python, the Anonymous function (A function without a name) is called the lambda function. The lambda function can accept multiple arguments with only one expression. It does not include any statement.
Syntax
lambda parameters: expressionExample :
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 functions are mostly used with built-in functions such as filter, map & reduce function
Let's go through most asked reverent queries with explanations
Scroll for More Useful Information and Relevant FAQs
Can we create multi-lines lambda functions?
No. Lambda function can receive multiple arguments but only one expression. Better go with a normal function created by using keyword def in case requires multiple lines of code.
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 a normal Python function.
Example 1:
def add5(x):
return x + 5
print("Each Number + 5:",map(add5, [1, 2, 3, 4]))
Output:
('Each Number + 5:', [6, 7, 8, 9])
Explanation: Here map function in combination with the 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 the same code using the lambda function.
Example 2:
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 the normal function in Example 1 and clubbed into one line of code using lambda in combination with the map function.
Brain Exercise
Was this post helpful?
- ?
Anonymous functions are created with the help of keyword:Options are:
- ?
What is the output for the following code?
add = lambda a, b, c : a + c print(add(2, 3, 5))
Try your hand at more Multiple-choice ExercisesOptions are: