In Python, you can use the if-else
construct within a lambda function to add multiple conditions. To add an elif
clause, you can nest another if-else
a statement within the first else
clause. This is also called the Python lambda elif statement.
The general syntax for adding an elif
a clause in a lambda function is:
lambda argument: true_value1 if condition1 else (true_value2 if condition2 else false_value)
Here, argument
is the input to the lambda function, condition1
is the first condition to be evaluated, true_value1
is the value to be returned if the first condition is true, condition2
is the second condition to be evaluated, true_value2
is the value to be returned if the second condition is true, and false_value
is the value to be returned if all the conditions are false.
For example, consider a lambda function that takes a number as input and returns “positive” if the number is greater than 0, “negative” if the number is less than 0, and “zero” if the number is equal to 0:
classify_num = lambda x: "positive" if x > 0 else ("zero" if x == 0 else "negative") print(classify_num(-5)) # Output: negative print(classify_num(0)) # Output: zero print(classify_num(10)) # Output: positive
In the above example, the lambda function first checks if the input number x
is greater than 0. If it is, it returns the string “positive”. If not, it checks if x
is equal to 0. If it is, it returns the string “zero”. If none of the conditions is true, it returns the string “negative”.