Keeping only some items
Half of real data work is filtering: keep the log lines that mention an error, the rows with a valid email, the scores above the cutoff. Python folds that job directly into comprehension syntax, so you should know both where the if goes and what it does there.
In lesson 1-1 every input item produced one output item. Often you also want to skip items. In Python for Beginners you did that with an if inside the loop:
evens = [] for n in nums: if n % 2 == 0: evens.append(n)
A comprehension does the same with an if at the end:
evens = [n for n in nums if n % 2 == 0]
Items that fail the test are simply left out of the new list. This trailing if is called the filter.
Code exercise · python
Run this program. The filter keeps only scores of 60 or higher.
if/else goes at the front, not the end
There is a second, different if you can use: the conditional expression A if test else B. It does not skip items, it chooses a value for every item. Because it is part of the value expression, it goes at the front:
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
Compare the two shapes:
| Shape | Where | Effect |
|---|---|---|
[x for x in xs if test] | end | keeps fewer items |
[a if test else b for x in xs] | front | same count, values chosen |
Mixing them up is the most common comprehension error, so pause on that table until it clicks.
Code exercise · python
Run this program. It combines both forms in one comprehension: the trailing if filters out entries that are empty after stripping, and the expression up front normalizes the survivors. This clean-then-keep shape is everyday data-cleaning code.
Code exercise · python
Your turn. Build `labels` so each number becomes the string "pass" if it is 60 or more, otherwise "fail". Print the result.
Quiz
How many items does [n for n in range(10) if n > 6] contain?