Python Lambda Function that returns True or False

Lambda Function that returns True or False in Python

In Python, we can define a Lambda Function that can return either True of False. Usually, this is a lambda function that returns a boolean value.

To return either True or False from a lambda function in Python, we have to use if else in the expression of lambda function.

The following is the structure of a typical lambda function that returns either True or False based on a condition.

lambda parameters: True if condition else False

For example, let us write a lambda function that takes a number as parameter, and returns True if the given number is even, or False if not.

lambda n: True if n % 2 == 0 else False

Examples

1. Lambda function that returns True if given number is Even, or False if not

In the following program, we define a lambda function, isEven, that returns True if given number is even, or False if the number is not even.

Python Program

isEven = lambda n: True if n % 2 == 0 else False
print("Is 8 even? ", isEven(8))
print("Is 7 even? ", isEven(7))
Run Code Copy

Output

Is 8 even?  True
Is 7 even?  False

Summary

In this tutorial of Python Lambda Functions, we learned how to write a lambda function that returns a boolean value, True or False.

Related Tutorials

Code copied to clipboard successfully 👍