In Python, lambda functions are a way to create small anonymous functions (functions without a name).
They are often used for simple operations and can contain only a single expression.
However, you can simulate the behavior of `if`, `else`, and `elif` conditions within a lambda function using conditional expressions (ternary operators).
Using if and else in lambda
The basic syntax for a lambda function with an if-else condition is:
lambda x: <expression1> if <condition> else <expression2>
This means that if <condition> is True, the lambda function will return <expression1>. Otherwise, it will return <expression2>.
Here is a code example:
func = lambda x: x * 2 if x > 10 else x + 2
print(func(12))
print(func(8))
Output
24
10
Using elif in lambda
Lambda functions do not directly support multiple elif statements because they are meant to be concise and simple.
However, you can nest if-else conditions to mimic the behavior of elif.
The basic syntax for a lambda function with an elif condition is:
lambda x: <expression1> if <condition1> else (<expression2> if <condition2> else <expression3>)
This is a nested if-else condition within a lambda function, simulating the elif.
Here is a code example:
func = lambda x: "High" if x > 15 else ("Medium" if x > 10 else "Low")
print(func(20))
print(func(12))
print(func(8))
Output
High
Medium
Low
Using conditional expressions in lambda functions allows decision-making within these small, one-line functions, enhancing their utility in various Python applications.
anonymous
Thanks for this post bro