Mapping Values with Conditional Expressions
In this lesson, you will learn how to use ternary operators inside list comprehensions to transform data differently based on specific criteria.
So far, you’ve used list comprehensions to filter items or create new lists based on existing data. Sometimes, however, you don't want to discard items—you want to modify them depending on whether they meet a certain condition. This is where the ternary operator (value_if_true if condition else value_if_false) becomes incredibly powerful when placed inside a list comprehension.
The Logic of Conditional Mapping
In a standard comprehension, the expression at the start defines what the final list contains. By inserting a ternary operator there, you can dictate the transformation logic per element.
Consider a list of test scores where you want to categorize them:
scores = [85, 42, 90, 60]
# Mapping scores to labels
results = ["Pass" if score >= 50 else "Fail" for score in scores]
print(results)
# Output: ['Pass', 'Fail', 'Pass', 'Pass']
Why This Matters
If you were to use a standard if clause at the end of the comprehension (e.g., [score for score in scores if score >= 50]), you would be filtering the list, losing the scores that didn't meet the criteria.
By placing the conditional expression at the beginning (the mapping portion), you keep every element of the original list but provide an alternative value for those that fail the test. This allows you to perform complex data normalization or labeling in a single, readable line of code. It transforms the list while preserving its length and the original order of items.
This technique is essential for data pipelines where you need to classify, normalize, or sanitize input data as it passes through your application.
Key Takeaway: Placing a ternary operator at the start of a list comprehension allows you to map every input to a new output based on conditional logic without losing elements from your sequence.