1318

How do I write an if-then-else statement in Python so that it fits on one line?

For example, I want a one line version of:

if count == N:
    count = 0
else:
    count = N + 1

In Objective-C, I would write this as:

count = count == N ? 0 : count + 1;
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Abizern
  • 146,289
  • 39
  • 203
  • 257

5 Answers5

2469

That's more specifically a ternary operator expression than an if-then, here's the python syntax

value_when_true if condition else value_when_false

Better Example: (thanks Mr. Burns)

'Yes' if fruit == 'Apple' else 'No'

Now with assignment and contrast with if syntax

fruit = 'Apple'
isApple = True if fruit == 'Apple' else False

vs

fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
LeoDog896
  • 3,472
  • 1
  • 15
  • 40
cmsjr
  • 56,771
  • 11
  • 70
  • 62
  • 3
    It's very much like comprehensions. You can do this: `print('matched!' if re.match(r'\d{4,}', '0aa9') else "nopes")` (assuming you import re) – uchuugaka May 20 '16 at 13:35
  • 11
    Note that the shorthand syntax is only valid for actual values. You can use it with constants and functions (`Yes' if fruit == 'Apple' else print('No Apple')`), but not with keywords (`'Yes' if fruit == 'Apple' else raise Exception('No Apple')`) – Torben Oct 28 '16 at 10:53
  • 7
    It is not clear to me if I can omit else, can I just have 'Yes' if fruit == 'Apple'? – Miro Feb 14 '17 at 02:14
  • 16
    You can't omit the else when using the ternary form, it results in a syntax error, but you could do a normal if in one line , I updated the samples to illustrate. – cmsjr Feb 15 '17 at 03:42
  • is it possible to use parenthesis in those statements? – Charlie Parker Feb 20 '17 at 21:29
  • 4
    This answer could be benefited by contrasting this method with the same thing using a multi-line if statement. – Brōtsyorfuzthrāx Aug 22 '17 at 00:11
  • This does not answer the original question "if/else on same line". - even though it does answer the specific example (ternary operator). – WestCoastProjects May 03 '18 at 12:41
  • This does not work. `print(" " .join(my_list)) if my_list else print("")` returns `SyntaxError: invalid syntax` – user5359531 Nov 16 '18 at 18:16
  • However it looks like you can use this format instead: `print(" " .join(my_list) if my_list else "" )` – user5359531 Nov 16 '18 at 18:19
  • When you haven't else statement: `when_condition_true if condition else None` – Yakir GIladi Edry Mar 07 '19 at 10:27
  • 2
    Why not this instead: isApple = fruit == 'Apple' – rcronk Mar 28 '19 at 16:54
  • 1
    For a case when the value want is a boolean and can be determined by comparison, that's fine. But consider the OP scenario. count = count == N ? 0 : count + 1; That would need to be like count = 0 if count == N else count + 1. – cmsjr Apr 02 '19 at 03:56
  • 1
    Can you type the first statement without the else keyword? For example, `value_when_true if condition` (without the else statement). I've tried it but it doesn't work. – KareemJ Apr 19 '19 at 20:42
  • Thankss! this question was posted about 10 years ago & it helped a guy from 2021 right now & that's me! – Ice Bear Jan 19 '21 at 06:00
  • I couldn't write something like this: `break if condition else continue` – Benyamin Jafari Jan 21 '21 at 11:38
  • cannot assign to conditional statement – Rajanboy May 12 '22 at 08:55
  • Thought it should be mentioned that PEP8 discourages this: ["Compound statements (multiple statements on the same line) are generally discouraged"](https://peps.python.org/pep-0008/#other-recommendations). So your linter might complain (though I personally have nothing against this style). – Scott G Jan 09 '23 at 00:06
293

Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.

if i > 3: print("We are done.")

or

field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural)) 
kale
  • 151
  • 1
  • 10
Johannes Braunias
  • 3,135
  • 1
  • 13
  • 8
  • 13
    Can someone explain why this isn't the best answer? Its definitely the easiest to read IMHO. – keithhackbarth Dec 20 '13 at 22:58
  • 66
    the question included an "else" condition – adam.r May 29 '14 at 18:56
  • 15
    @johannes-braunias Your method goes against PEP8 standards. – Ricky Wilson Jul 12 '14 at 07:05
  • 4
    From [PEP8](http://legacy.python.org/dev/peps/pep-0008/): Compound statements (multiple statements on the same line) are generally discouraged. – chishaku Jul 18 '14 at 17:01
  • 2
    Compound statements don't run in the shell without a line after them. With the extra line you might as well split them up. – Will S Feb 18 '15 at 15:55
  • 16
    That's weird. Here's a specific "Yes" example from [PEP8](http://legacy.python.org/dev/peps/pep-0008/#code-lay-out). `Yes: if x == 4: print x, y; x, y = y, x` I guess, you know, hobgoblins and whatnot. – anregen Jul 13 '17 at 22:04
  • 31
    PEP8 isn't holy writ. If your program would be better with this syntax, it's fine. – PProteus Aug 30 '18 at 11:11
  • 1
    The question looks more similar to a Generator Expression than a Compound Statement. That's why the other answer was marked as the best answer. PEP8 discourages Compound Statements (although it is not strictly forbidden), but a Generator Expression would be more acceptable (see [PEP289](https://www.python.org/dev/peps/pep-0289/)). – Jayce Jun 19 '19 at 08:35
168
count = 0 if count == N else N+1

- the ternary operator. Although I'd say your solution is more readable than this.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
146

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()
jameshfisher
  • 34,029
  • 31
  • 121
  • 167
mshsayem
  • 17,557
  • 11
  • 61
  • 69
  • 5
    This counts on an implementation detail that `(False, True) == (0, 1)` which I don't know is guaranteed (but didn't check). And though terse, it isn't going to win any readability awards. You can also do `"abcdefg"[i]` in C, but it doesn't mean you should. – msw May 10 '10 at 15:27
  • 10
    @msw: It's guaranteed that `False == 0` and `True == 1`: no implementation detail here. :) See the 'Booleans' heading under http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy – Mark Dickinson May 10 '10 at 16:13
  • 14
    But aren't both values computed, no matter what [] is? – tstenner May 10 '10 at 17:46
  • 1
    @msw: well, when it comes to ternary operations, I always prefer the first one. I just showed another possible way... – mshsayem May 11 '10 at 08:34
  • 1
    Another way: `{N: 0}.get(count, N+1)`. A third way, if `N+1` is some expensive function: `{N: 0}.get(count, "anything truthy") and f(N)`. This requires you to know the truthiness of the values of the dict, and they need to all have the same truthiness. If the values are all truthy, invert the boolean operator, e.g. `{0: 7}.get(weekday, False) or f(weekday)` – Jonas Kölker Nov 11 '13 at 16:27
  • 1
    count = [0,N+1][count==N] set of given solution is not functional in python 2.7 – magor Apr 06 '16 at 16:00
  • 1
    I am straggling to understand the concept behind putting the first assignment of value if the test evaluates as false in `[value_false, value_true][]` rather than the other way around (e.g. `value_true if else value_false`). Is there some logic behind this seemingly non intuitive syntax? – Tony Feb 20 '17 at 11:44
  • 1
    Because `False` evaluates to `0` and `True` evaluates to `1`. Though it works, avoid it. Usually it is a _bad_ way. – mshsayem Feb 22 '17 at 01:35
  • 1
    Is there a particular reason why a statement like this would fail ? `x+=1 if else y+=1` – LemonSnippet Mar 21 '19 at 19:14
  • 1
    Because the `if` syntax allows to put only _expression_; but `x+=1` is a _statement_. – mshsayem Mar 24 '19 at 05:02
29
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>

with your code-snippet it would become,

count = 0 if count == N else N + 1
phoenix24
  • 2,072
  • 2
  • 20
  • 24