Is there a ternary conditional operator in Python?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, it was added in version 2.5. The expression syntax is:
First
conditionis evaluated, then exactly one of eitheraorbis evaluated and returned based on the Boolean value ofcondition. Ifconditionevaluates toTrue, thenais evaluated and returned butbis ignored, or else whenbis evaluated and returned butais ignored.This allows short-circuiting because when
conditionis true onlyais evaluated andbis not evaluated at all, but whenconditionis false onlybis evaluated andais not evaluated at all.For example:
Note that conditionals are an expression, not a statement. This means you can’t use statements such as
pass, or assignments with=(or "augmented" assignments like+=), within a conditional expression:(In 3.8 and above, the
:="walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. But please don’t write code like that; it will quickly become very difficult to understand.)Similarly, because it is an expression, the
elsepart is mandatory:You can, however, use conditional expressions to assign a variable like so:
Or for example to return a value:
Think of the conditional expression as switching between two values. We can use it when we are in a ‘one value or another’ situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal
ifstatement instead.Keep in mind that it’s frowned upon by some Pythonistas for several reasons:
condition ? a : bternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python’s "surprising" behaviour use it (they may reverse the argument order).if‘ can be really useful, and make your script more concise, it really does complicate your code)If you’re having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example,
x = 4 if b > 8 else 9is read aloud asx will be 4 if b is greater than 8 otherwise 9.Official documentation: