Python lambda if statement | Example code

  • by

You can use if statement with 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 given value is module is zero or not.

res = lambda x: True if x % 2 == 0 else False


print(res(10))

Output:

Python lambda if statement

List comprehension with Lambda if condition

Use the filter function to get all values below to 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 and suggestions on this Python lambda tutorial.

Note: IDE: PyCharm 2021.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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.