Course contentsShow
← Python
Lesson 282 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Transforming Values Using Inline Ternary Operators

This lesson teaches how to apply conditional assignment within a comprehension to map values to different outputs based on runtime criteria.

Transforming Values Using Inline Ternary Operators

In this lesson, you will learn how to inject conditional logic directly into list comprehensions to map values to new outputs based on specific criteria.

Integrating Ternary Operators

Up until now, you have used if clauses in comprehensions primarily for filtering (keeping only items that meet a condition). However, if you want to transform an item based on a condition—like changing "fail" to "pass" or categorizing numbers—you need the ternary operator.

The ternary operator follows the syntax: value_if_true if condition else value_if_false. When placed inside a list comprehension, it determines what value gets added to the new list for every iteration.

Practical Application

Imagine you have a list of exam scores and want to create a list of "Pass" or "Fail" labels. Instead of writing a bulky for loop, you can condense this transformation into a single line:

scores = [45, 88, 72, 30]

# Transforming values using an inline ternary
results = ["Pass" if score >= 50 else "Fail" for score in scores]

print(results)
# Output: ['Fail', 'Pass', 'Pass', 'Fail']

In this example, the expression ("Pass" if score >= 50 else "Fail") is evaluated for every element in scores. Python checks the condition, chooses the appropriate string, and collects the result into the new list.

Why This Matters

Using inline ternary operators allows you to perform mapping operations that aren't strictly "filtering." Without this, you would be forced to break the logic out into a standard for loop or a separate helper function, which often adds unnecessary boilerplate. By keeping the transformation logic local to the comprehension, your code remains expressive and concise while clearly documenting the "if/else" relationship for every value you process.

Remember: The ternary operator in a comprehension acts on the output value, whereas a standard if clause acts as a filter for the entire element.

Key Takeaway: You can use the value_if_true if condition else value_if_false syntax inside a comprehension to transform items dynamically during iteration.