Conditional List Comprehensions
You can include conditional logic (if statements) within a list comprehension to filter the items from the iterable before they are added to the new list.
Syntax
[expression for item in iterable if condition]
Example 1: Filtering Even Numbers
We only want to include numbers that are divisible by 2.
python numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0] print(even_numbers) # [2, 4, 6, 8, 10]
Example 2: Filtering Strings by Length
python words = ['apple', 'cat', 'banana', 'dog', 'elephant']
short_words = [w for w in words if len(w) <= 4] print(short_words) # ['cat', 'dog']
Note on if...else in Comprehensions:
If you need an else clause (i.e., you want to transform the item one way if the condition is true, and a different way if false), the if/else part moves before the for loop.
Syntax: [value_if_true if condition else value_if_false for item in iterable]
python signals = [-1, 0, 5, -3, 10] statuses = ['Positive' if x > 0 else 'Non-positive' for x in signals] print(statuses)