Python developers commonly need to evaluate conditional expressions and take action based on the result, in their code. They generally use if-else statements for this purpose. But sometimes, you may need to concisely evaluate a condition and return value, all using a single line of code. In such cases, you can use ternary operator in Python. In this article, we will learn in detail about ternary operator in Python.
Ternary Operator in Python
A ternary operator in Python is a one line statement that allows you to evaluate a condition and assign value depending on whether the condition is true or false. It offers a shorter way to write an if-else statement. Here is an example of an if-else statement.
a = 10
if(a>5){
print('a>5')
}else{
print('a<=5')
}
In the above code, we basically check if the value of variable a is greater than 5 or not, and accordingly display an output message.
Even though our if-else condition is simple, the above code is verbose. You can easily shorten it using ternary operator. Here is its syntax.
true_value if condition else false_value
In the above statement, the condition will be first evaluated. If it is true, then true_value will be evaluated and returned, and false_value is ignored. Else false_value will be evaluated and returned, and true_value is ignored.
It is faster than conventional if else because when condition is true, only true_value is evaluated and false_value is not evaluated at all. On the other hand, when condition is false, false_value is evaluated and true_value is not evaluated at all. Here are a couple of examples to demonstrate its use.
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
There are some important points to keep in mind while using ternary operators.
1. The true_value and false_value need to be expressions and not statements. So you cannot use commands like pass, or assignments or even augmented assignments such as += in them. In all these cases, it will throw an error. Here are some examples to illustrate it. Even using parentheses around statements do not work.
>>> pass if true else pass
File "<stdin>", line 1
pass if true else pass
^
SyntaxError: invalid syntax
>>> a=1 if true else a=2
File "<stdin>", line 1
SyntaxError: can't assign to conditional expression
>>> (a=1) if true else (a=2)
File "<stdin>", line 1
(a=1) if true else (a=2)
^
SyntaxError: invalid syntax
Since Python 3.8+, you can also use walrus operator ‘:=’ to make simple assignments as expressions. But it can make the code very complicated. So use it only if you have to.
2. In a typical if-else statement, the else part is optional. But in case of ternary operator, the else part is mandatory. If you do not include it, you will get an error message as shown below.
>>> a=1
>>> a if True
File "<stdin>", line 1
a if True
3. Another point to keep in mind is that you can use ternary operator to assign variable values. Here is an example.
>>> a=1
>>> b=2
>>> x=a if True else b
>>> print(x)
1
In the above code, the result of ternary operator is assigned to variable x.
4. Since you can use it for variable assignment, you can also use ternary operator to return values from functions, as shown below.
>>> x=1
>>> y=2
>>> def check(x,y):
... return x if x>y else x
...
>>> check(a,b)
2
Now let us look at some other ways to use ternary operators in Python.
Nested Ternary Operator in Python
By default, the ternary operator can be difficult to use for complex use cases. To overcome this limitation, you can also use ternary operator in a nested manner, one inside the other. Here is its syntax.
true_value1 if condition1 else (true_value2 if condition2 else false_value)
Here is an example to illustrate it.
>>> x=1; y=2
>>> print("Both are equal" if x == y else "x > y" if x>y else "x < y")
x > y
In the above code, the outer ternary operator checks if x and y are equal. If yes, it will display ‘the corresponding ‘Both are equal’ message. Else the expression for its false_value checks if x>y. If this is true, then it displays ‘x>y’. Else it will display ‘x<y’.
Ternary Operator with Python Tuple
You can also use Ternary operator with 2-item Python tuple, where the first item is false_value and the 2nd item is true_value. Here is its syntax.
(false_value, true_value) [condition]
Here is an example to illustrate it.
>>> x=1;y=2
>>> ('x>y','x<=y')[x>y]
'x>y'
In the above example, our condition to be evaluated is x>y. Since x is not greater than y, this evaluates to false. In our tuple, the first value, that is ‘x>y’, is the false value. This is displayed.
Ternary Operator with Python Dictionary
Similarly, you can also use ternary operator with a Python dictionary containing 2 key-value pairs. In this case, one key needs to be True and its value needs to be the true value. The other key needs to be False, and its value should be the false value. Here is its syntax.
{True: true_value, False: false_value} [condition]
Here is an example to illustrate it.
>>> x=1;y=2
>>> {True:'x>y', False:'x<=y'}[x>y]
'x<=y'
In the above example, we have a dictionary with true value as ‘x>y’ and false value as ‘x<=y’. Our condition is x>y. Since this is not true, it displays ‘x<=y’.
Ternary Operator with Python Lambda
You can also use lambda with ternary operator just as we used tuple with ternary operator. The first item of tuple needs to be false value and the second item needs to be true value. Here is its syntax.
(lambda: false_value, lambda: true_value) [condition] ()
Here is an example to show how it works.
>>> x=1;y=2
>>> (lambda: 'x<=y', lambda: 'x>y') [x>y] ()
'x<=y'
Disadvantages of Python Ternary Operator
- Difficult to read – Since ternary operator is so concise, it can be difficult to understand for many Python developers. This is true, especially if your true/false expressions are complex.
- Error Prone – Since ternary operator tries to fit a lot of things in a single line, they are error prone. You can easily make a syntax error by incorrect order of expressions, missing colons and parentheses. This makes it even harder to debug.
- Non-standard – Generally, ternary operators have the format condition ? : true_value : false_value in most popular languages such as Java, C, C++, JavaScript, Ruby, Perl. But the ternary operator in Python has a different syntax. So it can be difficult for developers who are new to Python.
- Cannot Use Statements – Typical if-else statements allow you to use multiple statements within if/else blocks. Ternary operator requires you to use only expressions in if/else block. This is a major limitation.
- Difficult for Complex Use Cases – Due to the previous limitation, ternary operators are suitable for simple use cases only.
- Too many variations – As we saw above, there are many different ways to use ternary operator. It leads to a non-standard syntax, making it difficult for developers to understand other people’s code and maintain it.
Conclusion
In this article, we have learnt what are ternary operators in Python. We have also learnt how to use them in different ways. We also looked some of its limitations. Ternary operators are great if you want to shorten simple if-else statements, or if you want to assign result of if-else statement to a variable, or even return that value from a function. But if you want to execute statements in your if/else blocks, then you need to use the conventional if-else statement. Also, since there are so many different ways to use ternary operator in Python, it can confuse developers easily, and make your code difficult to maintain. Nevertheless, if it fits your use case, then ternary operator can be a good addition to your code.
FAQ
1. What is a Ternary Operator?
Ternary operator is a single line conditional expression that allows you to assign value based on result of condition. Its syntax is ‘true_value if condition else false_value’.
2. How to Use Ternary Operator in Python?
You can use ternary operator to evaluate condition and based on its result evaluate another expression in case the result is true. Else evaluate an expression if its result is false.
3. When to use Ternary Operator?
You can use ternary operator, if you want to implement a simple if-else statement with easy to understand condition and expressions. You can also use it if you want to easily assign a value or return a value as a result of if-else statement. You can also use it if your true and false expressions are one-liners and not multiple statements.
4. When not to use Ternary Operators?
If you want to implement complex if-else statements, or if you need to run multiple statements in if/else blocks, then ternary operators will not be suitable. In fact, if you need to run statements instead of expressions in true_value/false_value then also ternary operator will not work.
5. How to read ternary operator statements in Python?
If you encounter a ternary operator as ‘x = 1 if b > 2 else 3’ then you can read it as ‘x will be 1 if b is greater than 2 otherwise 3’.
Also read:
How to Read Large File in Python
How to Execute System Command in Python
How to Check If File Exists in Python
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.