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 ...
Some other articles
Y104 - Lists and Tuples Embedding more complex code into a named block Shuffling a list - Ruby and Python Collections in Python - list tuple dict and string. Spike solutions and refactoring - a Python example Stepping through a list (or an array) in reverse order List slices in Python - 2 and 3 values forms, with an uplifting example All possible combinations from a list (Python) or array (Ruby) Beware - a=a+b and a+=b are different - Python Arrays of arrays - or 2D arrays. How to program tables. Copying - duplicating data, or just adding a name? Perl and Python compared Traffic lights in Python Python - fresh examples of all the fundamentals Strings as collections in Python Creating and iterating through Python lists Looking for a value in a list - Python Tektronix 4010 series / Python Tuples for loop - how it works (Perl, PHP, Java, C, etc) Python collections - mutable and imutable Python - extend v append on a list This article Overloading of operators on standard objects in Python Y103 - Conditionals and Loops Conditional operators in Python Equality (in Python) Method, Class, Module, Package - how to they relate in Python? Setting up and tearing down with the Python with keyword Finding sum, minimum, maximum and average in Python (and Ruby) Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) If elif elif elif - multiway selection in Python Identity in Python Flowchart to program - learning to program with Well House Learning to program - the if statement. Python. Finding the total, average, minimum and maximum in a program Python or Lua - which should I use / learn? Python for loops - applying a temporary second name to the same object Does a for loop evaluate its end condition once, or on every iteration? How a for loop works Java, Perl and other languages Python - fresh examples from recent courses Groupsave tickets - 3 or 4 train tickets for the price of 2 Learning to program in Python 2 ... and / or in Python 3 Saying NOT in Perl, PHP, Python, Lua ... Equality, sameness and identity - Python Decisions - small ones, or big ones? No switch in Python Python is like a narrowboat Python - when to use the in operator New - Conditional expressions in Python 2.5 Python - block insets help with documentation This article Wimbledon Neck What - no switch or case statement? P206 - More Loops and Conditionals While, for, foreach or something else to loop. Ruby v Perl - a comparison example Perl - making best use of the flexibility, but also using good coding standards How a for loop works Java, Perl and other languages Some more advanced Perl examples from a recent course Multiway branches in Perl - the given and when syntax Alternative loops and conditionals in Ruby and Perl Are you learning Perl? Some more examples for you! A pint of Black Rat, and a lazy barman Setting a safety net or fallback value in Perl switch and case, or given and when in Perl For loop - checked once, or evety time? Ruby v Perl comparison and contrast Question Mark - Colon operator (Perl and PHP) Saying NOT in Perl, PHP, Python, Lua ... Ruby, C, Java and more - getting out of loops for loop - how it works (Perl, PHP, Java, C, etc) Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages This article What - no switch or case statement? Perl - redo and last without a loop H104 - Control Statements Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) While, for, foreach or something else to loop. Flowchart to program - learning to program with Well House Does a for loop evaluate its end condition once, or on every iteration? How a for loop works Java, Perl and other languages Predictions for the seagull population Extracting real data from an exported file in PHP or Perl Question Mark - Colon operator (Perl and PHP) Saying NOT in Perl, PHP, Python, Lua ... Decisions - small ones, or big ones? for loop - how it works (Perl, PHP, Java, C, etc) Testing for one of a list of values. Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages Double and Triple equals operator in PHP This article Don't repeat code - use loops or functions Assignment, equality and identity in PHP Wimbledon Neck Code and code maintainance efficiency