Lambda Functions: If Statements

By Hemanta Sundaray on 2022-03-07

Learn about lambda expressions in Python in my blog post here

We can make lambda functions more complex using a modified form of an if statement. For example, consider the following function:

def result(x):
    if x >= 40:
        return "PASS"
    else:
        return "FAIL"

print(result(45))

Below is a lambda function that does the same thing:

result = lambda x: "PASS" if x >= 40 else "FAIL"

In general, the syntax for an if statement in a lambda function is:

lambda x: [OUTCOME IF TRUE] if [CONDITIONAL] else [OUTCOME IF FALSE]

Join the Newsletter