Main Content

The ternary operator in Python

Archive - Originally posted on "The Horse's Mouth" - 2006-03-25 17:18:24 - Graham Ellis

The ? : operator that you may have come across in Perl, PHP, C and Java - known as the ternary or conditional operator - is ABSENT from Python. "But it's so useful" I hear you cry. Ah yes, but isn't this elegant:

val = float(raw_input("Age: "))
status = ("working","retired")[val>65]
print "You should be",status


UPDATE ... There IS now a "ternary" operator in Python (recent versions of Python 2, and Python 3) ... this post was orginally made in March 2006 ...

Footnote - the ? : operator in those other languages gives you a very convening short form of if, then, else where you can select a value based on a condition for printing or assigning to a variable; here's a Perl or PHP example:

$status = ($val > 65) ? "retired" : "working";

Great, useful, but yet another oddball structure on the language - I'm forever having to explain how an operator can have three operands and how you MUST have a : if you have a ? ... but in Python it's so natural to use a tuple ...