0

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

jpp
  • 159,742
  • 34
  • 281
  • 339
Leiradk
  • 21
  • 4
  • *Don't* use a `lambda`: `def a(x): return x - (x > 1)` – jpp Feb 07 '19 at 06:58
  • [PEP8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations): "Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier." – jpp Feb 07 '19 at 08:51
  • ok Thank you @PEP8 – Leiradk Feb 07 '19 at 10:32

2 Answers2

2
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.

himank
  • 439
  • 3
  • 5
1

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

taurus05
  • 2,491
  • 15
  • 28