In this lesson, you will learn how to chain multiple conditional checks within a single comprehension to handle multi-state data transformation requirements.
Moving Beyond Simple Logic
So far, you’ve used basic ternary operators—value_if_true if condition else value_if_false—inside your comprehensions to transform data. But what happens when you have more than two outcomes? For example, categorizing a list of student scores into "Excellent," "Pass," or "Fail."
Instead of breaking this out into a bulky for loop, you can nest ternary operators directly within your comprehension. Think of it as a ladder of conditions: Python checks the first if, and if it's false, it moves into the else block, which contains another ternary operator to check the next condition.
The Nested Syntax
The structure follows this pattern: A if condition1 else (B if condition2 else C).
Here is how you might process a list of scores:
scores = [95, 75, 40]
# Classify scores into three tiers
results = [
"Excellent" if s >= 90 else ("Pass" if s >= 60 else "Fail")
for s in scores
]
print(results)
# Output: ['Excellent', 'Pass', 'Fail']
Why This Matters
By nesting these operators, you keep your data transformation logic compact and expressive. You are essentially creating a "decision tree" that evaluates each item in your iterable against multiple benchmarks simultaneously.
While it is tempting to nest these deeply, keep in mind that readability is key. If you find yourself nesting more than two or three levels deep, it is often a signal that your logic is becoming too complex for a single line. However, for three-way or four-way categorization, this approach is a powerful tool in your Python toolkit for writing concise, functional-style code.
Key Takeaway: Nested ternary operators allow you to handle multi-state data transformations within a single comprehension by chaining conditional expressions inside the else clause.