Advertisement
Advertisement


How to condense if/else into one line in Python?


Question

Possible Duplicate:
Python Ternary Operator
Putting a simple if-then statement on one line

Is there a way to compress an if/else statement to one line in Python?
I oftentimes see all sorts of shortcuts and suspect it can apply here too.

2018/07/09
1
131
7/9/2018 9:22:59 AM


Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
2012/07/17

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0
2012/07/17

There is the conditional expression:

a if cond else b

but this is an expression, not a statement.

In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:

if something: somefunc()
else: otherfunc()

but this is discouraged as a matter of formatting-style.

2012/07/17