Two moves that turn a pile of rows into an answer. Filter: keep only the rows that match a condition. Group: one count (or total) per category. Both are Unit 2–3 tools, combined.
Watch how the code picks out rows that meet a condition — that’s filtering. Enrolled in our Runestone course? Open it from there so your progress counts.
Big Data. 5.6 cleaned the data. Today you slice it: one subset, one category at a time. The exam’s most common data item — “what does this loop with an IF compute?” — is this lesson at small scale.
Filter = selection (Unit 2) inside traversal (Unit 3). Keep a row only if it passes a test. Aggregate = combine many values into one: a count, a total, an average, a max. Grouping = one aggregate per category.
def count_where(rows, field, value): count = 0 for row in rows: if row[field] == value: count = count + 1 return count for food in ["Pizza", "Salad", "Burrito"]: print(food, count_where(rows, "choice", food))
PROCEDURE countWhere(list, value) { count ← 0 FOR EACH item IN list { IF (item = value) { count ← count + 1 } } RETURN(count) } FOR EACH food IN ["Pizza", "Salad", "Burrito"] { DISPLAY(countWhere(choices, food)) }
Hover or tap a line to light its twin. The parameter is the twist. One procedure, called once per category, gives the whole grouped count — and a procedure with a parameter is exactly what the Create PT asks for.
Filter, then aggregate. To answer “most popular lunch among 12th graders,” build the subset first:
seniors = [] for row in rows: if row["grade"] == "12": # still a string — it came from a CSV seniors.append(row) for food in ["Pizza", "Salad", "Burrito", "Pasta"]: print(food, count_where(seniors, "choice", food))
18 lunch orders. Pick a filter, then step through the rows and watch each tally grow. Does the most popular choice change when you filter?
Five questions. AP lists start at index 1.
An overall number can be true and still hide something important. A city where “average commute is 22 minutes” might have one neighborhood averaging 50. A school with a high pass rate might have one group far below it. Filtering and grouping are how you find out who the average is hiding — and they’re how fairness problems in data get caught.
count_where or average_by is the required procedure.