Home » Python » Python condense if/else to one line? [duplicate]

Python condense if/else to one line? [duplicate]

Posted by: admin November 30, 2017 Leave a comment


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.


An example of Python’s way of doing “ternary” expressions:

i = 5 if a > 7 else 0

translates into

if a > 7:
   i = 5
   i = 0

This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I’m not sure it helps that much in creating readable code.

The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.

It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It’s worth a read just based on those posts.


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

>>> 'true' if True else 'false'
>>> 'true' if False else 'false'


Only for using as a value:

x = 3 if a==2 else 0


return 3 if a==2 else 0


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.