Lambda function is a small anonymous function, which means it does not have any name.
It is defined using lambda keyword instead of def.
It is a single-line function, mainly used for throwaway functions that are needed temporarily.
Syntax of Lambda Function
lambda arguments: expression
⦁ lambda: keyword to define the lambda function.
⦁ arguments: input parameters
⦁ expression: a single expression that gets evaluated and returned (like the body of the function)
Example
# Normal function
def add(x, y):
return x + y
print(add(2, 3)) # Output: 5
# Lambda function
add_lambda = lambda x, y: x + y
print(add_lambda(2, 3)) # Output: 5
When to Use Lambda Functions
⦁ When you need a short function for immediate use.
⦁ You're working with functions like map(), filter(), reduce(), or sorted().
⦁ You want cleaner and more concise code.
More example for you to practice
1. addition = lambda x, y: x + y
print(addition(2,3)) # Output: 5
2. multiplication = lambda a, b: a * b
print(multiplication(2, 3)) # Output: 6
3. full_name = lambda first_name, last_name: f"{first_name} {last_name}"
print(full_name("ash", "luv")) # Output: ash luv
If this helped you understand lambda functions better, consider supporting me 💛
