Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambda with if but without else

I was writing some lambda functions and couldn't figure this out. Is there a way to have something like lambda x: x if (x<3) in python? As lambda a,b: a if (a > b) else b works ok. So far lambda x: x < 3 and x or None seems to be the closest i have found.

like image 878
root Avatar asked Oct 03 '12 13:10

root


People also ask

Can lambda function be defined without ELSE clause?

Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.

Can you put an if statement in a lambda?

Using if-else in lambda function The lambda function will return a value for every validated input. Here, if block will be returned when the condition is true, and else block will be returned when the condition is false.

Can you do Elif in lambda?

Technically we cannot use an elif statement in a lambda expression. However, we can nest if else statements within an else statement to achieve the same result as an elif statement.

How do you do if in lambda Python?

Use lambda function syntax to use an if statement in a lambda function. Use the syntax lambda input: true_return if condition else false_return to return true_return if condition is True and false_return otherwise. condition can be an expression involving input .


1 Answers

A lambda, like any function, must have a return value.

lambda x: x if (x<3) does not work because it does not specify what to return if not x<3. By default functions return None, so you could do

lambda x: x if (x<3) else None 

But perhaps what you are looking for is a list comprehension with an if condition. For example:

In [21]: data = [1, 2, 5, 10, -1]  In [22]: [x for x in data if x < 3] Out[22]: [1, 2, -1] 
like image 151
unutbu Avatar answered Sep 29 '22 09:09

unutbu