Filtering in Comprehensions
In this tutorial, we'll include only the values that pass a condition.
You can add an if condition to a comprehension to keep only some values.
Normal loop:
numbers = [1, 2, 3, 4, 5]
evens = []
for number in numbers:
if number % 2 == 0:
evens.append(number)
Comprehension:
numbers = [1, 2, 3, 4, 5]
evens = [number for number in numbers if number % 2 == 0]
Output:
[2, 4]
The Shape
[expression for item in collection if condition]
The condition decides whether the item is included.
Transform and Filter
You can transform values and filter them at the same time:
words = ["apple", "cat", "banana"]
long_words = [word.upper() for word in words if len(word) > 3]
Output:
["APPLE", "BANANA"]
Keep It Readable
Filtering comprehensions are useful, but do not make them too clever. If you need multiple conditions and several calculations, use a normal loop.
Filtering Without Changing
Sometimes the expression is just the original item:
names = ["Ada", "", "Grace"]
real_names = [name for name in names if name != ""]
This keeps only the non-empty strings. You are not transforming the names; you are only filtering them.
Practice
Start with a list of scores. Build a new list containing only scores greater than or equal to 50.