Skip to content

lambda if-else Python | Function code

  • by

Python lambda if-else function is used to choose a return value based on some condition.

Syntax: if-else in lambda function is a little tricky

lambda <arguments> : <Return Value if condition is True> if <condition> else <Return Value if condition is False>

Simple

lambda <arguments> : <value_1> if <condition> else <value_2>

Using if else in Lambda function Python

Simple example code Lambda Function with If Else Condition.

Example 1

if the given value is between 10 and 20 then it will return True else it will return False.

foo = lambda x: True if (10 < x < 20) else False

print(foo(12))
print(foo(3))

Output:

lambda if else Python

Example 2

A lambda function that returns the square of the number if the number is even, else cube of the number.

x = lambda n: n ** 2 if n % 2 == 0 else n ** 3

print(x(4))
print(x(3))

Output:

16
27

Example 3

Using filter() function with a conditional lambda function with if-else. Filter numbers between 10 to 20 only.

Num = [1, 3, 33, 12, 34, 56, 11, 19, 21, 34, 15]

res = list(filter(lambda x: 10 < x < 20, Num))
print('Filtered List : ', res)

Output: Filtered List : [12, 11, 19, 15]

Keep in mind that while lambda functions are useful for short, one-line expressions, for more complex logic, it’s often better to use a regular named function. Lambda functions are limited to a single expression and can’t include statements or multiple expressions.

Do comment if you have any doubts or suggestions on this Python lambda topic.

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading