Python Ternary Operator Assignment 1

There are a lot of computer languages that include the ternary (or tertiary) operator, which is basically a one-line conditional expression in Python. If you’re interested, you can read about the various ways it’s rendered in other languages over on Wikipedia. Here we will spend some time looking at several different examples and why you might use this operator in real life.

I remember using the ternary operator in C++ where it was a question mark. I looked it up with Google and found some good example in a StackOverflow question and answer and in that aforementioned Wikipedia example. Let’s take a look at some of those and see if we can figure them out. Here is one of the simplest examples:

x = 5 y = 10 result = Trueif x > y elseFalse

This basically reads as follows: The result will be True is x is greater than y, otherwise the result is False. To be honest, this reminds me mightily of some of the Microsoft Excel conditional statements I’ve seen. Some people object to this format, but it’s what the official Python documentation uses. The following is how you would write it in a normal conditional statement:

x = 5 y = 10   if x > y: print"True"else: print"False"

So you would save 3 lines of code by using the ternary operator. Anyway, you might want to use this structure when you’re looping over a set of files and you want to filter out some sections or rows. For our next example, we’ll loop over some numbers and check if they are odd or even:

for i inrange(1, 11): x = i %2 result = "Odd"if x else"Even"print"%s is %s"%(i, result)

You would be surprised how often you have to check the remainder of a division statement. This is a quick way to tell if the number is odd or even though. In the previously mentioned StackOverflow link, there’s this funny piece of code that is shown as an example for those people who are still using Python 2.4 or older:

# (falseValue, trueValue)[test]>>>(0, 1)[5>6]   0>>>(0, 1)[5<6]   1

This is rather ugly, but it does the job. This is indexing a tuple and is certainly a hack, but it’s an interesting bit of code. Of course, it doesn’t have the short-circuit value of the newer method that we looked at previously, so both values are evaluated. You may even run into oddball errors doing it this way where True is False and vice-versa, so I don’t really recommend it.

There are also several ways to do the ternary with Python’s lambda. Here’s one from the Wikipedia entry mentioned earlier:

def true(): print"true"return"truly"def false(): print"false"return"falsely"   func = lambda b,a1,a2: a1 if b else a2 func(True, true, false)()   func(False, true, false)()

This is some funky code, especially if you don’t understand how lambdas work. Basically, a lambda is an anonymous function. Here we create two normal functions and a lambda one. Then we call it with a boolean True and a False. In the first call, it’s read as follows: call the true function if boolean True, else call the false function. The second is slightly more confusing as it appears to say that you should call the true method if boolean False, but it’s really saying it will call the false method only if b is boolean False. Yeah, I find that a bit confusing too.

Wrapping Up

There are several other examples of ternary operators in the “additional reading section below that you can check out, but at this point you should have a pretty good grasp of how to use it and perhaps when you’d use it. I would personally use this methodology when I know I have a simple True/False conditional I need to make and I want to save a few lines of code. However, I often tend to go with explicit over implicit because I know that I’ll have to come back and maintain this code and I don’t like having to figure out weird stuff like this all the time, so I would probably just go ahead and write the 4 lines. The choice is yours, of course.

Additional Reading

6. Ternary Operators¶

Ternary operators are more commonly known as conditional expressions in Python. These operators evaluate something based on a condition being true or not. They became a part of Python in version 2.4

Here is a blueprint and an example of using these conditional expressions.

Blueprint:

Example:

It allows to quickly test a condition instead of a multiline if statement. Often times it can be immensely helpful and can make your code compact but still maintainable.

Another more obscure and not widely used example involves tuples. Here is some sample code:

Blueprint:

Example:

This works simply because True == 1 and False == 0, and so can be done with lists in addition to tuples.

The above example is not widely used and is generally disliked by Pythonistas for not being Pythonic. It is also easy to confuse where to put the true value and where to put the false value in the tuple.

Another reason to avoid using a tupled ternery is that it results in both elements of the tuple being evaluated, whereas the if-else ternary operator does not.

Example:

This happens because with the tupled ternary technique, the tuple is first built, then an index is found. For the if-else ternary operator, it follows the normal if-else logic tree. Thus, if one case could raise an exception based on the condition, or if either case is a computation-heavy method, using tuples is best avoided.

condition_is_trueifconditionelsecondition_is_false
is_fat=Truestate="fat"ifis_fatelse"not fat"
(if_test_is_false,if_test_is_true)[test]
fat=Truefitness=("skinny","fat")[fat]print("Ali is ",fitness)# Output: Ali is fat
condition=Trueprint(2ifconditionelse1/0)#Output is 2print((1/0,2)[condition])#ZeroDivisionError is raised
Categories: 1

0 Replies to “Python Ternary Operator Assignment 1”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *