Filtering Rows

Selecting the rows you meant, and noticing how many you dropped.

A filter is a comprehension with a test

Say the condition once, in one place. Scattering the same test through the code is how two parts of an analysis end up disagreeing about who counts.

rows = [{"score": 92}, {"score": 58}, {"score": 88}]
passing = [r for r in rows if r["score"] >= 60]
print(len(passing))

Count what you removed

A filter that quietly drops most of the data changes the answer more than any calculation after it. Printing the before and after is one line and catches it.

rows = [{"score": 92}, {"score": 58}]
kept = [r for r in rows if r["score"] >= 60]
print(len(rows), "->", len(kept))

Exercise

Try It Yourself

Write passing(rows, mark) that returns the rows whose score is at least mark.

Press Run to see output

Check Your Understanding