By Devoted

2008-12-27 08:32:18 8 Comments

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?


@Vinko Vrsalovic 2008-12-27 08:44:19

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

a if condition else b

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

For example:

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

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

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

You can, however, use conditional expressions to assign a variable like so:

x = a if True else b

Think of the conditional expression as switching between two values. It is very useful when you're in a 'one value or another' situation, it but doesn't do much else.

If you need to use statements, you have to use a normal if statement instead of a conditional expression.

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

  • The order of the arguments is different from those of the classic condition ? a : b ternary 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).
  • 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. (Although the 'inline 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 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

@yota 2016-01-25 15:07:08

The order may seems strange for coders however f(x) = |x| = x if x > 0 else -x sounds very natural to mathematicians. You may also understand it as do A in most case, except when C then you should do B instead...

@Kal Zekdor 2016-03-06 09:23:11

Be careful with order of operations when using this. For example, the line z = 3 + x if x < y else y. If x=2 and y=1, you might expect that to yield 4, but it would actually yield 1. z = 3 + (x if x > y else y) is the correct usage.

@Kal Zekdor 2016-04-15 00:36:05

The point was if you want to perform additional evaluations after the conditional is evaluated, like adding a value to the result, you'll either need to add the additional expression to both sides (z = 3 + x if x < y else 3 + y), or group the conditional (z = 3 + (x if x < y else y) or z = (x if x < y else y) + 3)

@MrGeek 2017-05-26 15:31:44

what if there are multiple conditions ?

@Dimesio 2017-08-09 06:08:33

@MrGeek, you could group the boolean expressions. "foo" if (bool or bool && bool or etc) else "bar"

@MrGeek 2017-08-09 09:17:55

@Dimesio I meant something like if (c1) a1 elif (c2) a2 elif ... else a(n).

@Dimesio 2017-08-11 00:04:32

@MrGeek, I see what you mean, so you would basically be nesting the operations: ` "foo" if Bool else ("bar" if Bool else "foobar") `

@Albert van der Horst 2018-06-17 12:50:52

Programmers need precise correct formulation even more than mathematician, because in mathematics there is always a resort to underlying concepts. A convincing argument is the % operator, mimicking the way "mod" is used in math would have been a disaster. So no, I don't accept your argument. It is like adhering to imperial units. Groetjes Albert

@BeMyGuestPlease 2019-09-08 15:02:18

For the expression: 'x and y' and 'x or y' and their return values I recommend checking‌​ons and also the other post:…

@Baldrickk 2019-10-10 13:45:06

@KalZekdor I read that and expected 1... It took me a few seconds to see how you had to read it to make 4 a possibility.

@QtRoS 2020-01-30 11:18:05

Go doesn't have ternary operator, bro.

@Gerard ONeill 2020-03-09 23:35:39

Nice explanation, but short circuiting doesn't mean what you think it means - it means that the rest of the condition isn't evaluated if the 'truthiness' of the entire condition can be decided early. Statement 'b' is never evaluated even in languages without short circuiting. Ex: if (arr != null && arr[0] = 1)...

@user118967 2020-05-19 16:47:24

Other answers correctly talk about the Python ternary operator. I would like to complement by mentioning a scenario for which the ternary operator is often used but for which there is a better idiom. This is the scenario of using a default value.

Suppose we want to use option_value with a default value if it is not set:

run_algorithm(option_value if option_value is not None else 10)

or simply

run_algorithm(option_value if option_value else 10)

However, an ever better solution is simply to write

run_algorithm(option_value or 10)

@Baruc Almaguer 2020-03-26 21:59:43

I find cumbersome the default python syntax val = a if cond else b, so sometimes I do this:

iif = lambda (cond, a, b): a if cond else b
# so I can then use it like:
val = iif(cond, a, b)

Of course, it has the downside of always evaluating both sides (a and b), but the syntax it's way clearer to me

@eatsfood 2020-04-28 16:57:59

This seems to be twice the amount of work, more RAM usage and more obfuscated than the simpler val = a if cond else b statement.

@Todd 2020-03-11 06:49:39

Python has a ternary form for assignments; however there may be even a shorter form that people should be aware of.

It's very common to need to assign to a variable one value or another depending on a condition.

>>> li1 = None
>>> li2 = [1, 2, 3]
>>> if li1:
...     a = li1
... else:
...     a = li2
>>> a
[1, 2, 3]

^ This is the long form for doing such assignments.

Below is the ternary form. But this isn't most succinct way - see last example.

>>> a = li1 if li1 else li2
>>> a
[1, 2, 3]

With Python, you can simply use or for alternative assignments.

>>> a = li1 or li2
>>> a
[1, 2, 3]

The above works since li1 is None and the interp treats that as False in logic expressions. The interp then moves on and evaluates the second expression, which is not None and it's not an empty list - so it gets assigned to a.

This also works with empty lists. For instance, if you want to assign a whichever list has items.

>>> li1 = []
>>> li2 = [1, 2, 3]
>>> a = li1 or li2
>>> a
[1, 2, 3]

Knowing this, you can simply such assignments whenever you encounter them. This also works with strings and other iterables. You could assign a whichever string isn't empty.

>>> s1 = ''
>>> s2 = 'hello world'
>>> a = s1 or s2
>>> a
'hello world'

I always liked the C ternary syntax, but Python takes it a step further!

I understand that some may say this isn't a good stylistic choice because it relies on mechanics that aren't immediately apparent to all developers. I personally disagree with that viewpoint. Python is a syntax rich language with lots of idiomatic tricks that aren't immediately apparent to the dabler. But the more you learn and understand the mechanics of the underlying system, the more you appreciate it.

@Walter Tross 2019-02-09 18:23:18

One of the alternatives to Python's conditional expression

"yes" if boolean else "no"

is the following:

{True:"yes", False:"no"}[boolean]

which has the following nice extension:

{True:"yes", False:"no", None:"maybe"}[boolean_or_none]

The shortest alternative remains:

("no", "yes")[boolean]

but there is no alternative to

yes() if boolean else no()

if you want to avoid the evaluation of yes() and no(), because in

(no(), yes())[boolean]  # bad

both no() and yes() are evaluated.

@That's Enam 2019-10-23 07:22:58

is_spacial=True if gender = "Female" else (True if age >= 65 else False)


it can be nested as your need. best of luck


@Frank 2019-10-16 08:37:26

As already answered, yes there is a ternary operator in python:

<expression 1> if <condition> else <expression 2>

Additional information:

If <expression 1> is the condition you can use Short-cirquit evaluation:

a = True
b = False

# Instead of this:
x = a if a else b

# You could use Short-cirquit evaluation:
x = a or b

PS: Of course, a Short-cirquit evaluation is not a ternary operator but often the ternary is used in cases where the short circuit would be enough.

@Simon Zimmermann 2010-05-27 07:56:06

<expression 1> if <condition> else <expression 2>

a = 1
b = 2

1 if a > b else -1 
# Output is -1

1 if a > b else -1 if a < b else 0
# Output is -1

@Roy Tinker 2010-10-04 21:14:21

This one emphasizes the primary intent of the ternary operator: value selection. It also shows that more than one ternary can be chained together into a single expression.

@Jon Coombs 2014-12-01 21:30:51

@Craig , I agree, but it's also helpful to know what will happen when there are no parentheses. In real code, I too would tend to insert explicit parens.

@Yaakov Bressler 2019-05-12 13:03:48

A neat way to chain multiple operators:

f = lambda x,y: 'greater' if x > y else 'less' if y > x else 'equal'

array = [(0,0),(0,1),(1,0),(1,1)]

for a in array:
  x, y = a[0], a[1]

# Output is:
#   equal,
#   less,
#   greater,
#   equal

@gorsky 2009-12-06 11:51:50

Unfortunately, the

(falseValue, trueValue)[test]

solution doesn't have short-circuit behaviour; thus both falseValue and trueValue are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue and falseValue could be methods and have side-effects).

One solution to this would be

(lambda: falseValue, lambda: trueValue)[test]()

(execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it doesn't solve the case when using properties.

And so the story goes - choosing between 3 mentioned solutions is a trade-off between having the short-circuit feature, using at least Зython 2.5 (IMHO not a problem anymore) and not being prone to "trueValue-evaluates-to-false" errors.

@Perkins 2018-10-11 17:34:51

While the tuple of lambdas trick works, it takes roughly 3x as long as the ternary operator. It's only likely to be a reasonable idea if it can replace a long chain of if else if.

@Simplans 2016-08-21 17:56:26

Ternary Operator in different programming Languages

Here I just try to show some important difference in ternary operator between a couple of programming languages.

Ternary Operator in Javascript

var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0

Ternary Operator in Ruby

a = true ? 1 : 0
# 1
b = false ? 1 : 0
# 0

Ternary operator in Scala

val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0

Ternary operator in R programming

a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0

Ternary operator in Python

a = 1 if True else 0
# 1
b = 1 if False else 0
# 0

@fralau 2018-01-10 17:12:28

It may sound opinionated; but what it essentially says is that it the Python syntax is likely to be understood by a person who never saw a ternary operator, while very few people will understand the more usual syntax unless they have been told first what it means.

@Albert van der Horst 2018-06-17 12:55:29

Algol68: a=.if. .true. .then. 1 .else. 0 .fi. This may be expressed also a=(.true.|1|0) As usual Algol68 is an improvement over its successors.

@Andy Fedoroff 2018-12-25 13:04:23

Many programming languages derived from C usually have the following syntax of ternary conditional operator:

<condition> ? <expression1> : <expression2>

At first, the Python Benevolent Dictator For Life (I mean Guido van Rossum, of course) rejected it (as non-Pythonic style), since it's quite hard to understand for people not used to C language. Also, the colon sign : already has many uses in Python. After PEP 308 was approved, Python finally received its own shortcut conditional expression (what we use now):

<expression1> if <condition> else <expression2>

So, firstly it evaluates the condition. If it returns True, expression1 will be evaluated to give the result, otherwise expression2 will be evaluated. Due to Lazy Evaluation mechanics – only one expression will be executed.

Here are some examples (conditions will be evaluated from left to right):

pressure = 10
print('High' if pressure < 20 else 'Critical')

# Result is 'High'

Ternary operators can be chained in series:

pressure = 5
print('Normal' if pressure < 10 else 'High' if pressure < 20 else 'Critical')

# Result is 'Normal'

The following one is the same as previous one:

pressure = 5

if pressure < 20:
    if pressure < 10:

# Result is 'Normal'

Hope this helps.

@shivtej 2018-12-06 14:45:27

a if condition else b

Just memorize this pyramid if you have trouble remembering:

  if           else
a                   b 

@PythonLover 2018-10-21 20:14:53

YES, python have a ternary operator, here is the syntax and an example code to demonstrate the same :)

#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false

a= input("Enter the First Number ")
b= input("Enter the Second Number ")

print("A is Bigger") if a>b else print("B is Bigger")

@PythonLover 2018-10-21 20:45:54

I have added a one line statement example to check which number is big to elaborate it further

@Thierry Lathuille 2018-10-21 21:52:56

print is really not a good choice, as this will give a SyntaxError in Python2.

@PythonLover 2018-10-21 21:54:21

@Thierry Lathuille here I used print() function not print statement, print function is for Python 3 while print statement is for Python 2

@Thierry Lathuille 2018-10-21 21:58:23

The question has already been asked on SO, just try it with Python 2 and you will see by yourself. 'print('hello') is a perfectly valid syntax in Python 2.7, but the way it is parsed makes your code above throw a SyntaxError.

@ewwink 2018-04-26 15:41:32

if variable is defined and you want to check if it has value you can just a or b

def test(myvar=None):
    # shorter than: print myvar if myvar else "no Input"
    print myvar or "no Input"


will output

no Input
no Input
no Input

@Perkins 2018-10-11 17:13:50

While useful for similar problems, this is not a ternary conditional. It works to replace x if x else y, but not x if z else y.

@Ali Hallaji 2018-04-04 14:02:17

Ternary conditional operator simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :

[on_true] if [expression] else [on_false]

1- Simple Method to use ternary operator:

# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)  # Output: 10

2- Direct Method of using tuples, Dictionary, and lambda:

# Python program to demonstrate ternary operator
a, b = 10, 20
# Use tuple for selecting an item
print( (b, a) [a < b] )
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
# lamda is more efficient than above two methods
# because in lambda  we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) # in output you should see three 10

3- Ternary operator can be written as nested if-else:

# Python program to demonstrate nested ternary operator
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
        if a > b else "b is greater than a")

Above approach can be written as:

# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
    if a > b:
        print("a is greater than b")
        print("b is greater than a")
    print("Both a and b are equal") 
# Output: b is greater than a

@Perkins 2018-10-11 17:28:46

Note that the ternary operator is smaller (in memory) and faster than the nested if. Also, your nested if-else isn't actually a rewrite of the ternary operator, and will produce different output for select values of a and b (specifically if one is a type which implements a weird __ne__ method).

@Natesh bhat 2017-08-20 07:31:02

you can do this :-

[condition] and [expression_1] or [expression_2] ;


print(number%2 and "odd" or "even")

This would print "odd" if the number is odd or "even" if the number is even.

The result :- If condition is true exp_1 is executed else exp_2 is executed.

Note :- 0 , None , False , emptylist , emptyString evaluates as False. And any data other than 0 evaluates to True.

Here's how it works:

if the condition [condition] becomes "True" then , expression_1 will be evaluated but not expression_2 . If we "and" something with 0 (zero) , the result will always to be fasle .So in the below statement ,

0 and exp

The expression exp won't be evaluated at all since "and" with 0 will always evaluate to zero and there is no need to evaluate the expression . This is how the compiler itself works , in all languages.


1 or exp

the expression exp won't be evaluated at all since "or" with 1 will always be 1. So it won't bother to evaluate the expression exp since the result will be 1 anyway . (compiler optimization methods).

But in case of

True and exp1 or exp2

The second expression exp2 won't be evaluated since True and exp1 would be True when exp1 isn't false .

Similarly in

False and exp1 or exp2

The expression exp1 won't be evaluated since False is equivalent to writing 0 and doing "and" with 0 would be 0 itself but after exp1 since "or" is used, it will evaluate the expression exp2 after "or" .

Note:- This kind of branching using "or" and "and" can only be used when the expression_1 doesn't have a Truth value of False (or 0 or None or emptylist [ ] or emptystring ' '.) since if expression_1 becomes False , then the expression_2 will be evaluated because of the presence "or" between exp_1 and exp_2.

In case you still want to make it work for all the cases regardless of what exp_1 and exp_2 truth values are, do this :-

[condition] and ([expression_1] or 1) or [expression_2] ;

@moi 2017-10-20 06:37:01

If you want to use that in the context of x = [condition] and ([expression_1] or 1) or [expression_2] and expression_1 evaluates to false, x will be 1, not expression_1. Use the accepted answer.

@kenorb 2015-05-05 12:00:09

An operator for a conditional expression in Python was added in 2006 as part of Python Enhancement Proposal 308. Its form differ from common ?: operator and it's:

<expression1> if <condition> else <expression2>

which is equivalent to:

if <condition>: <expression1> else: <expression2>

Here is an example:

result = x if a > b else y

Another syntax which can be used (compatible with versions before 2.5):

result = (lambda:y, lambda:x)[a > b]()

where operands are lazily evaluated.

Another way is by indexing a tuple (which isn't consistent with the conditional operator of most other languages):

result = (y, x)[a > b]

or explicitly constructed dictionary:

result = {True: x, False: y}[a > b]

Another (less reliable), but simpler method is to use and and or operators:

result = (a > b) and x or y

however this won't work if x would be False.

A possible workaround is to make x and y lists or tuples as in the following:

result = ((a > b) and [x] or [y])[0]


result = ((a > b) and (x,) or (y,))[0]

If you're working with dictionaries, instead of using a ternary conditional, you can take advantage of get(key, default), for example:

shell = os.environ.get('SHELL', "/bin/sh")

Source: ?: in Python at Wikipedia

@Walter Tross 2019-02-09 18:07:40

result = {1: x, 0: y}[a > b] is another possible variant (True and False are actually integers with values 1 and 0)

@Aaron Hall 2015-11-17 19:14:33

Does Python have a ternary conditional operator?

Yes. From the grammar file:

test: or_test ['if' or_test 'else' test] | lambdef

The part of interest is:

or_test ['if' or_test 'else' test]

So, a ternary conditional operation is of the form:

expression1 if expression2 else expression3

expression3 will be lazily evaluated (that is, evaluated only if expression2 is false in a boolean context). And because of the recursive definition, you can chain them indefinitely (though it may considered bad style.)

expression1 if expression2 else expression3 if expression4 else expression5 # and so on

A note on usage:

Note that every if must be followed with an else. People learning list comprehensions and generator expressions may find this to be a difficult lesson to learn - the following will not work, as Python expects a third expression for an else:

[expression1 if expression2 for element in iterable]
#                          ^-- need an else here

which raises a SyntaxError: invalid syntax. So the above is either an incomplete piece of logic (perhaps the user expects a no-op in the false condition) or what may be intended is to use expression2 as a filter - notes that the following is legal Python:

[expression1 for element in iterable if expression2]

expression2 works as a filter for the list comprehension, and is not a ternary conditional operator.

Alternative syntax for a more narrow case:

You may find it somewhat painful to write the following:

expression1 if expression1 else expression2

expression1 will have to be evaluated twice with the above usage. It can limit redundancy if it is simply a local variable. However, a common and performant Pythonic idiom for this use-case is to use or's shortcutting behavior:

expression1 or expression2

which is equivalent in semantics. Note that some style-guides may limit this usage on the grounds of clarity - it does pack a lot of meaning into very little syntax.

@JSDBroughton 2016-02-18 13:05:59

expression1 or expression2 being similar and with the same drawbacks/positives as expression1 || expression2 in javascript

@Aaron Hall 2016-05-27 04:37:39

Thanks, @selurvedu - it can be confusing until you get it straight. I learned the hard way, so your way might not be as hard. ;) Using if without the else, at the end of a generator expression or list comprehension will filter the iterable. In the front, it's a ternary conditional operation, and requires the else. Cheers!!

@tchrist 2019-01-26 14:12:47

@AaronHall Although your use of metasyntactic expressionN for all instances is consistent, it might be easier to understand with naming that distinguished the conditional test expression from the two result expressions; eg, result1 if condition else result2. This is especially evident when nesting (aka chaining): result1 if condition1 else result2 if condition2 else result3. See how much better that reads this way?

@Aaron Hall 2019-01-26 18:24:21

@tchrist thanks for the review - if you look at the revision history, this post currently has two revisions. Most of my other answers, especially the top ones, have been revisited again and again. This answer never gets my attention because the community wiki status gives me no credit for the content, and so I never see any votes on it. As I don't really have time for an edit on this right now, frog knows when it will come to my attention again in the future. I can see you've edited the top answer, so feel free to borrow/quote my material from this post in that one (and cite me if apropos!)

@Todor Minakov 2016-05-11 07:13:31

More a tip than an answer (don't need to repeat the obvious for the hundreth time), but I sometimes use it as a oneliner shortcut in such constructs:

if conditionX:

, becomes:

print('yes') if conditionX else print('nah')

Some (many :) may frown upon it as unpythonic (even, ruby-ish :), but I personally find it more natural - i.e. how you'd express it normally, plus a bit more visually appealing in large blocks of code.

@frederick99 2017-08-20 06:07:17

I prefer print( 'yes' if conditionX else 'nah' ) over your answer. :-)

@Todor Minakov 2017-10-26 11:40:17

That is if you want to print() in both cases - and it looks a bit more pythonic, I have to admit :) But what if the expressions/functions are not the same - like print('yes') if conditionX else True - to get the print() only in truthy conditionX

@Thierry Lathuille 2018-10-21 21:51:29

To add to Frederick99's remark, another reason to avoid print('yes') if conditionX else print('nah') is that it gives a SyntaxError in Python2.

@Todor Minakov 2018-10-22 04:09:00

The only reason it gives a syntax error is because in Python 2 print is a statement - print "yes", while in Python 3 it is a function - print("yes"). That can be resolved by either using it as a statement, or better - from future import print_function.

@Michael Burr 2008-12-27 08:44:23

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.

@Landon Kuhn 2009-01-22 18:58:09

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>)]

@SilverbackNet 2011-02-04 02:25:24

Note that this one always evaluates everything, whereas the if/else construct only evaluates the winning expression.

@Dustin Getz 2012-03-08 19:31:48

(lambda: print("a"), lambda: print("b"))[test==true]()

@martineau 2012-05-31 18:20:15

It should be noted that what's within the []s can be an arbitrary expression. Also, for safety you can explicitly test for truthiness by writing [bool(<expression>)]. The bool() function has been around since v2.2.1.

@jskulski 2015-05-28 20:57:14

Is this idiomatic in python? Seems confusing but maybe its convention

@Dr. Drew 2016-02-19 07:49:50

Ugly is in the eye of the beholder, and I don't find this ugly at all. It concisely make elegant use of the fact that bool is a subclass of int and that Python indexes are 0-based. Admittedly, it's probably not the most efficient (as @SilverBackNet mentioned, both options are eval'd). However, this works perfectly for deciding between 1 of 2 strings as @Claudiu said - I use it for this all the time. For example: '%d item%s to process!'%(num_items,('','s')[num_items > 1]) or 'Null hypothesis %s be rejected (p-val = %0.4f)'%(("can't",'must')[pval<alpha],pval).

@JDM 2016-03-01 18:43:37

I've done a similar trick -- only once or twice, but done it -- by indexing into a dictionary with True and False as the keys: {True:trueValue, False:falseValue}[test] I don't know whether this is any less efficient, but it does at least avoid the whole "elegant" vs. "ugly" debate. There's no ambiguity that you're dealing with a boolean rather than an int.

@Breezer 2017-11-29 13:59:33

This trick may help avoid timing based attacks on algorithms if it always evaluates both possible results and avoids skipping code (an 'if' skips).

@Baldrickk 2019-10-10 13:48:45

@jskulski only in old python, before 2.5. Even then though, if cond: [expression_1] else: [expression_2] was more common

@James Brady 2008-12-27 10:48:27

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.

1. Is there an equivalent of C’s ”?:” ternary operator?

@ThomasH 2009-10-21 15:33:59

The remedy is to use (test and [true_value] or [false_value])[0], which avoids this trap.

@volcano 2014-01-13 07:52:08

Ternary operator usually executes faster(sometimes by 10-25%).

@OrangeTux 2014-08-05 12:30:33

@volcano Do you have source for me?

@mbomb007 2018-03-19 20:59:54

@OrangeTux Here's the disassembled code. Using the method ThomasH suggested would be even slower.

@Sasikiran Vaddi 2013-11-20 10:44:12

Simulating the python ternary operator.

For example

a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()


'b greater than a'

@Grijesh Chauhan 2013-12-27 05:50:06

Why not simply result = (y, x)[a < b] Why do you uses lambda function ?

@glglgl 2014-02-13 08:14:33

@GrijeshChauhan Because on "compliated" expressions, e. g. involving a function call etc., this would be executed in both cases. This might not be wanted.

@Benoit Bertholon 2013-01-14 15:56:09

You might often find

cond and on_true or on_false

but this lead to problem when on_true == 0

>>> x = 0
>>> print x == 0 and 0 or 1 
>>> x = 1
>>> print x == 0 and 0 or 1 

where you would expect for a normal ternary operator this result

>>> x = 0
>>> print 0 if x == 0 else 1 
>>> x = 1
>>> print 0 if x == 0 else 1 

@Paolo 2012-04-25 11:40:11

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.

@user3317 2012-09-26 09:09:29

The behaviour is not identical - q("blob", on_true, on_false) returns on_false, whereas on_true if cond else on_false returns on_true. A workaround is to replace cond with cond is not None in these cases, although that is not a perfect solution.

@Jonas Kölker 2013-11-11 16:11:06

Why not bool(cond) instead of cond is True? The former checks the truthiness of cond, the latter checks for pointer-equality with the True object. As highlighted by @AndrewCecil, "blob" is truthy but it is not True.

@Arseny 2014-02-24 11:51:08

Wow, that looks really hacky! :) Technically, you can even write [on_false, on_True][cond is True] so the expression becomes shorter.

@Hucker 2019-03-28 14:08:20

There is no short circuit in this answer. If on_true and on_false are expensive to call this is a bad answer.

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] What are metaclasses in Python?

33 Answered Questions

[SOLVED] What does if __name__ == "__main__": do?

20 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

42 Answered Questions

[SOLVED] What does the "yield" keyword do?

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

36 Answered Questions

[SOLVED] What is the !! (not not) operator in JavaScript?

  • 2009-04-24 08:13:58
  • Hexagon Theory
  • 593130 View
  • 3206 Score
  • 36 Answer
  • Tags:   javascript operators

44 Answered Questions

[SOLVED] Replacements for switch statement in Python?

25 Answered Questions

[SOLVED] What is the "-->" operator in C++?

4 Answered Questions

[SOLVED] What does the ??!??! operator do in C?

  • 2011-10-19 16:56:59
  • Peter Olson
  • 263435 View
  • 2013 Score
  • 4 Answer
  • Tags:   c operators trigraphs

Sponsored Content