Does Python have a ternary conditional operator like C does

+4 votes
The ternary operator functions like an if-else construct that is packed into a single statement. Is it possible to create this in python?
Apr 13, 2018 in Python by kaalabilli
• 1,090 points
2,505 views

6 answers to this question.

+3 votes
Best answer

Yes, the syntax is:

a if condition else b

If the condition is true, the expression takes the value of a, else it will be b.


answered Apr 13, 2018 by Nietzsche's daemon
• 4,260 points

selected Oct 12, 2018 by Omkar
+1 vote

Yes, it was added in version 2.5.
The syntax is:

a if condition else b

First condition is evaluated, then either a or b is returned based on the Boolean value of condition
If condition evaluates to True a is returned, else b is returned.

For example:

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

Note that conditionals are an expression, not a statement. This means you can't use assignments or pass or other statements in a conditional:

>>> pass if False else x = 3
  File "<stdin>", line 1
    pass if False else x = 3
          ^
SyntaxError: invalid syntax

In such a case, you have to use a normal if statement instead of a conditional.


Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons.

If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

answered Oct 12, 2018 by findingbugs
• 4,780 points
+1 vote

You can index into a tuple:

(falseValue, trueValue)[test]

test needs to return True or False.
It might be safer to always implement it as:

(falseValue, trueValue)[test == True]

or you can use the built-in bool() to assure a Boolean value:

(falseValue, trueValue)[bool(<expression>)]
answered Oct 12, 2018 by abc
+1 vote

For versions prior to 2.5, there's the trick:

[expression] and [on_true] or [on_false]

It can give wrong results when on_true has a false boolean value.1
Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.

answered Oct 12, 2018 by rani
+1 vote

From the documentation:

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

See PEP 308 for more details about conditional expressions.

New since version 2.5.

answered Oct 12, 2018 by kalpesh
+1 vote

For Python 2.5 and newer there is a specific syntax:

[on_true] if [cond] else [on_false]

In older Pythons a ternary operator is not implemented but it's possible to simulate it.

cond and on_true or on_false

Though, there is a potential problem, which if cond evaluates to True and on_true evaluates to False then on_false is returned instead of on_true. If you want this behavior the method is OK, otherwise use this:

{True: on_true, False: on_false}[cond is True] # is True, not == True

which can be wrapped by:

def q(cond, on_true, on_false)
    return {True: on_true, False: on_false}[cond is True]

and used this way:

q(cond, on_true, on_false)

It is compatible with all Python versions.

answered Oct 12, 2018 by Progba

Related Questions In Python

0 votes
1 answer

To simulate construct of other language does Python have a ternary conditional operator?

You can index into a tuple: (falseValue, trueValue)[test] test needs ...READ MORE

answered Oct 15, 2018 in Python by findingbugs
• 4,780 points
662 views
0 votes
1 answer

Does Python have a ternary conditional operator?

Think of the conditional expression as switching ...READ MORE

answered Nov 2, 2020 in Python by Gitika
• 65,770 points
585 views
0 votes
0 answers

Does Python have a ternary conditional operator?

If Python doesn't have a ternary conditional ...READ MORE

Apr 19, 2022 in Python by Edureka
• 13,620 points
477 views
0 votes
0 answers

Does Python have a ternary conditional operator?

Is there a ternary conditional operator in ...READ MORE

Sep 21, 2022 in Python by Samuel
• 460 points
452 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,454 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,108 views
+4 votes
7 answers

Splitting a List into chunks in Python

Here's a generator that yields the chunks ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
35,453 views
+1 vote
8 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
36,048 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP