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

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

An example of Pythons way of doing ternary expressions:

i = 5 if a > 7 else 0

translates into

if a > 7:
   i = 5
else:
   i = 0

This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise Im 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. Its worth a read just based on those posts.

Pythons if can be used as a ternary operator:

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

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

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0

Leave a Reply

Your email address will not be published.