222

How might I compress an if/else statement to one line in Python?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
AnovaVariance
  • 2,415
  • 2
  • 14
  • 6
  • 1
    http://stackoverflow.com/questions/1686390/python-equivalent-of-short-form-if-in-c http://docs.python.org/reference/compound_stmts.html – TheZ Jul 17 '12 at 19:15
  • 3
    That's the question you wanted to link: http://stackoverflow.com/questions/394809/python-ternary-operator – Kijewski Jul 17 '12 at 19:17
  • 2
    another reference: http://stackoverflow.com/questions/7778400/is-there-control-flow-in-python – clwen Jul 17 '12 at 19:17
  • ***This*** is the question I was thinking of: http://stackoverflow.com/questions/11491944/better-way-than-using-if-else-statement-in-python – Levon Jul 17 '12 at 19:26
  • 1
    Conditional expressions don't cover all cases (or all versions). Now what? – Brent Bradburn Feb 05 '13 at 19:57

4 Answers4

371

An example of Python's 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 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.

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
  • 2
    How do i use it in the return statement? `return count if (count * (distance < within_radius)) > 0 else (continue)` – technazi Oct 31 '18 at 23:38
  • How can I use a boolean list in between? `list = 5 if [boolean list] else 0`? – Dan Li Jan 04 '23 at 18:58
71

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

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
sloth
  • 99,095
  • 21
  • 171
  • 219
  • Just want to add the "true" command-line one-line syntax for the that. I have searched a lot how to do that, but no one answer contains this information: $ python -c "import sys; var=1; [ sys.stdout.write('POS\n') if var>0 else sys.stdout.write('NEG\n')]" – Alexander Samoylov Oct 08 '18 at 10:38
43

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0
f p
  • 3,165
  • 1
  • 27
  • 35
29

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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384