Filtering Data During Iteration with Conditional Expressions
In this lesson, you will learn how to combine conditional logic and iteration into a single, elegant expression to extract exactly the data you need.
When processing large datasets, you often encounter situations where you only want to transform or collect elements that meet specific business requirements. While a standard for loop with an if statement works, Python allows you to perform this filtering directly within a comprehension. This keeps your code concise and readable.
The Syntax of Conditional Filtering
The structure follows a simple pattern: [expression for item in iterable if condition].
Imagine you are managing an online store and have a list of product prices. You need to apply a discount only to items that cost more than $100. Instead of writing a multi-line loop, you can process this in one line:
prices = [45, 120, 85, 250, 30]
# Filter items over 100 and apply a 10% discount
discounted_prices = [price * 0.9 for price in prices if price > 100]
print(discounted_prices)
# Output: [108.0, 225.0]
Why use this approach?
By placing the if clause at the end of the comprehension, you tell Python to evaluate the condition before the expression is applied to the result list. If the condition evaluates to False, the item is skipped entirely.
This is particularly useful when you need to clean data on the fly. For instance, if you have a list of user inputs and need to extract valid email addresses that contain the "@" symbol:
raw_data = ["alice@example.com", "bob-no-email", "charlie@web.com", "invalid-entry"]
valid_emails = [email for email in raw_data if "@" in email]
print(valid_emails)
# Output: ['alice@example.com', 'charlie@web.com']
This method is superior to traditional loops when you are performing straightforward filtering and mapping tasks. It minimizes the "noise" in your code, allowing the intent—what you are filtering and why—to remain the focal point.
Key Takeaway: Use conditional expressions within comprehensions to combine filtering and transformation into a single, clean operation that keeps your data processing logic declarative and concise.