Estimated reading time: 2 minutes
Python introduced a ternary conditional operator in version 2.5, enabling a compact way to write conditionals within expressions. While traditional if-else statements work well for complex conditions, the ternary operator allows a more concise expression, making your code cleaner and easier to read.
This guide will cover the syntax, usage examples, and best practices for Python’s ternary operator, along with situations where a regular if-else
might be preferable.
TL;DR
In Python, the ternary conditional operator allows concise, inline conditional expressions:
a if condition else b
Table of contents
Syntax of the Ternary Conditional Operator in Python
The ternary operator’s syntax in Python is:
a if condition else b
Here’s how it works:
- Condition is evaluated first.
- If the condition is
True
, a is returned. - If the condition is
False
, b is returned.
Example
Consider a scenario where you want to assign a value based on a condition:
x = 'Positive' if number > 0 else 'Non-Positive'
If number
is greater than 0, x
will be 'Positive'
; otherwise, x
will be 'Non-Positive'
.
Why Use a Ternary Operator?
The ternary operator is helpful in cases where you need to choose between two values based on a condition, and you want to keep the code concise. This can be especially useful in function return values, variable assignments, or any situation where brevity is beneficial.
Best Practices and Limitations
- Avoid Complex Expressions: Since the ternary operator should be concise, it’s best not to include complex logic within the expression. When the condition becomes lengthy, a standard
if-else
is clearer. - Readability: While the ternary operator can make your code more concise, overuse can lead to reduced readability, especially for those new to Python.
- Remember the Order: Python’s ternary operator syntax differs from other languages (e.g.,
condition ? a : b
in C or JavaScript). Thea if condition else b
format can be confusing if you’re accustomed to other languages’ ternary structures.
Advanced Example: Using Ternary in Functions
A ternary operator can also be useful in function returns. For example, a basic max function can use it:
def my_max(a, b):
return a if a > b else b
This function returns a
if a
is greater than b
; otherwise, it returns b
.
Additional Resources
- Stack Overflow: Does Python have a ternary conditional operator?
- Python Documentation on Conditional Expressions
- PEP 308 – Conditional Expressions