Show the different ways to filter inside a Python comprehension, including choosing a value per item.
There are two things in a comprehension that look like filtering, and they do completely different jobs. The example below shows both of them next to each other.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# An if clause filters, so items that fail are left out entirely.
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Filter and transform together.
squares_of_evens = [n * n for n in numbers if n % 2 == 0]
print(squares_of_evens) # [4, 16, 36, 64, 100]
# A conditional expression changes the value, not the selection.
labels = [n if n < 5 else -n for n in numbers]
print(labels) # [1, 2, 3, 4, -5, -6, -7, -8, -9, -10]
# More than one if means both of them must pass.
print([n for n in numbers if n % 2 == 0 if n > 5]) # [6, 8, 10]
The if clause sits after the for clause, and it drops the items that do not satisfy it, so the result is shorter than the input. The conditional expression sits before the for clause, and it runs for every item and chooses one of two values, so the result is exactly as long as the input. That is the distinction to be able to state clearly.
You can use both of them together, which means you filter first and then transform the survivors, and that is what the squares_of_evens line does. The order inside a comprehension is fixed by the syntax. You write the expression, then the for clause, and then the if clauses. The if clauses are checked before the expression runs, so the expression never sees the items that were filtered out.
Two more if clauses can be chained, and then all of them must pass. The last line keeps the even numbers that are also greater than 5, which gives 6, 8, and 10. There is no or clause available, so a choice between two conditions needs a single condition that uses or, such as n % 2 == 0 or n % 3 == 0. That is the usual way round it.