Leiradk
Leiradk

Reputation: 21

How to put a return statement in lambda python with expression?

I'm planning to simplify my code without defining the function. Is it possible?

a = lambda x:1 if x>1 return x-1 else return x

output 0 = 0, 1=1 ,2=1 ,3=2

Upvotes: 0

Views: 230

Answers (2)

himank
himank

Reputation: 439

a = lambda x:1 if x>1 return x-1 else return x 

This is syntactically wrong. If you want to use if else, inline to make it work like a ternary operator in other languages. You will have to write:

# expression1 if condition else expression2
x-1 if x>1 else x

So it becomes:

a = lambda x: x-1 if x>1 else x

Remember lambda in python can only have a single line of code.

Upvotes: 2

taurus05
taurus05

Reputation: 2546

This is syntactically correct way to use lambdas in Python

>>> a = lambda x: x-1 if x>1 else x
>>> a(3)
2
>>> a(1)
1
>>> a(0)
0
>>> a(2)
1  

For better understanding about lambdas visit this link

Upvotes: 1

Related Questions