Lambda with if but without else in Python

Hello Friends, in this tutorial we will look at what happens when we write a lambda function with if statement and do not use else and what happens if we use if along with else in lambda function.

Let’s see first what is Lambda function in Python…

Lambda function is an anonymous function that can have any number of arguments and must have a return value. To know more about lambda function please check out this link – Lambda Function In Python. Here you will understand clearly.

Now we look at some usage of lambda functions:

square = lambda x: x*x

print(square(4))

And the output of the above two lines of code will be:

16

If we use if statement in this lambda function then:

mod = lambda x: x if(x > 0)

print(mod(4))

And the output of the above code:

File "lambda.py", line 1
    mod = lambda x: x if(x > 0)
                                   ^
SyntaxError: invalid syntax

The above code on execution shows Syntax error, as we know that a lambda function must return a value and this function, returns x if x > 0 and it does not specify what will be returned if the value of x is 0 or negative.

To correct it we need to specify else part that is what will be returned if x is non-positive.

mod = lambda x: x if(x > 0) else -x

print(mod(4))

Output:

4

Thank You…

I hope you have a clear idea of the Python Lambda function without else and using only the if.

 

Leave a Reply