How to apply an if statement in Python lambda if

Share Your Love

Hello guys, in Python, you can use the conditional operator ‘if’ in a Python lambda if function to create a simple if-else statement. The syntax for this is:

lambda argument: true_value if condition else false_value

Here, argument is the input to the lambda function, condition is the condition to be evaluated, true_value is the value to be returned if the condition is true, and false_value is the value to be returned if the condition is false.

For example, consider a lambda function that takes a number as input and returns “even” if the number is even and “odd” if the number is odd:

is_even = lambda x: "even" if x % 2 == 0 else "odd"
print(is_even(3))   # Output: odd
print(is_even(4))   # Output: even

In the above example, the lambda function lambda x: "even" if x % 2 == 0 else "odd" checks if the input number x is divisible by 2. If x is even, it returns the string “even”, and if x is odd, it returns the string “odd”.

You can also use multiple conditions with the if-else statement in a lambda function. Here is an example that returns “positive” if the input is greater than 0, “negative” if the input is less than 0, and “zero” if the input is equal to 0:

check_sign = lambda x: "positive" if x > 0 else ("negative" if x < 0 else "zero")
print(check_sign(-5))   # Output: negative
print(check_sign(0))    # Output: zero
print(check_sign(10))   # Output: positive

So, in the end, we learn here how to apply an if statement in Python with a lambda if statement.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter