Ternary operator in Python

doug
Mon, 05 Jul 2010 20:31:32 +0000

People are always wondering if Python has a ternary operator. The answer is yes but no.

There is no recognised ternary operator. However it is very simple to construct one out of logic operations.

Python short circuits conditional evaluations. This means that given a series of logic operations, if it can plainly see that a certain branch of that logic is unreachable or of no consequence it wont even attempt to execute it.

An example:

def f():
  print "In f"
  return False
def g():
  print "In g"
  return True

f() and g()

This will only print "In f" and will never reach g. Since that, that condition is known never to be True already.

We can apply the same thought process to build a ternary operator using and's and or's.

In addition to the two functions above, let's introduce another.

def h(number):
  print "In h"
  return number > 0

Now let's see our first attempt at a ternary operator.

# h is our condition, g is our action if h is true, f otherwise.

# Condition will be True
h(1) and g() or f()

# Condition will be False
h(-1) and g() or f()

This looks good. It seems to work. However, there is a case to be aware of given the short circuiting nature.

# This time f will be our action if h is true, g otherwise.

# Pass 1
h(1) and f() or g()

# Pass 2
h(-1) and f() or g()

This does not work! So what happened? Pass 2 works fine but on pass 1 all three functions are called. This is as a result of h being True it tries f which is False so it finally tries g.

So your "true condition" case (in this case f) must always evaluate to True in order to stop it rolling onto the or. This is easily solved to give us our result.

h(1) and (f() or True) or g()

Admitedly that isn't as pretty as a true ternary operator but it works, is logically sound and will allow you to perform conditions within things like Python's lambda functionality.

doif = lambda condition, truedo, falsedo : condition and (truedo() or True) or falsedo()
doif(h(1), f, g)
doif(h(-1), f, g)

Fun times shall be had by all!

As a final note. This same logic can be applied to absolutely any language that features short-circuiting condition evaluation.