Lambda Function in Python
In Python, an anonymous function, also known as lambda function, is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
Syntax lambda arguments: expression
- lambda → Keyword used to define the function.
- arguments → Input values (like parameters in normal functions).
- expression → A single expression that gets evaluated and returned automatically.
Example: Basic Lambda Function.
Python
# Normal function
def add(a, b):
return a + b
# Lambda function
add_lambda = lambda a, b: a + b
# Both work the same way
print(add(3, 5)) # Output: 8
print(add_lambda(3, 5)) # Output: 8 Explanation:
- The lambda function takes two arguments (a and b) and returns their sum.
- We don’t need the return keyword — it’s implicitly returned.