You can use the if statement with the lambda function in Python. Python lambda if returns a value based on conditional logic.
Syntax
lambda x: True if x % 2 == 0 else False
Python lambda if statement example
Simple example code, check whether given value is module is zero or not.
res = lambda x: True if x % 2 == 0 else False
print(res(10))
Output:
List comprehension with Lambda if the condition
Use the filter function to get all values below 3 from the given list.
data = [1, 2, 5, 10, 3]
res = filter(lambda x: x < 3, data)
print(list(res))
Output: [1, 2]
if and else in Python lambda expression
test = lambda x: True if (x > 10 and x < 20) else False
print((test(10)))
Output: False
Do comment if you have any doubts or suggestions on this Python lambda tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.