Filtering Elements Using Conditional Logic
In this lesson, you will learn how to refine your list comprehensions by adding if clauses to selectively include only the data you need.
The Power of Conditional Filtering
Previously, we used basic list comprehensions to transform every item in a collection. But what if you only want to keep the items that meet a specific requirement? Instead of writing a bulky for loop with an if statement inside, you can perform the filtering directly within the list comprehension syntax.
By placing an if clause at the very end of your comprehension, Python evaluates the boolean condition for each item. If the condition evaluates to True, the item is added to your new list. If it is False, the item is simply skipped.
A Concrete Example
Imagine you have a list of test scores and you want to extract only the passing grades (scores of 60 or higher). Instead of creating an empty list and using append(), you can do it in one expressive line:
scores = [45, 88, 52, 95, 30, 70]
# Only include scores greater than or equal to 60
passing_scores = [s for s in scores if s >= 60]
print(passing_scores)
# Output: [88, 95, 70]
Why This Matters
This syntax is more than just a shortcut; it makes your code declarative. By stating "keep the score if the score is at least 60," you make your logic much easier for other developers to read at a glance. You are essentially combining the transformation phase and the filtering phase into a single, clean operation.
Remember that the if clause acts as a gatekeeper. It must appear after the loop definition (the for part) but before the closing bracket of the list comprehension. If you find yourself frequently using for loops just to discard unwanted items, this conditional logic is your new best friend for keeping your codebase clean and efficient.
Key Takeaway: You can use an if clause at the end of a list comprehension to act as a filter, ensuring only elements that satisfy your boolean condition are included in the resulting list.