AP CSP Day 6: List Traversal And Filtering
Share
List traversal uses a FOR EACH loop to process every element in a list sequentially. Filtering is a common traversal pattern where elements meeting a condition are collected into a new list or counted. On the AP CSP exam, list traversal questions often show pseudocode that iterates through a list and applies a conditional to each element, asking students to predict the final state of a result list or counter variable. Carefully tracking which elements pass the filter condition is key.
📚 Study the Concept First (Optional) Click to expand ▼
List Traversal and Filtering
What Is Traversal?
Traversal means visiting every element in a list exactly once. A FOR EACH loop in AP CSP pseudocode handles this automatically, assigning each element in order to the loop variable.
Filtering Pattern
Filtering collects elements that meet a condition into a new list. The pattern: create an empty result list, traverse the original list, and append each element that passes the condition.
Practice Question
What is displayed after the following code runs?
nums ← [3, 8, 1, 6, 2]
result ← []
FOR EACH num IN nums
{
IF num > 4
{
APPEND(result, num)
}
}
DISPLAY(LENGTH(result))The loop checks each element against the condition num > 4. Evaluating each: 3 > 4 is false, 8 > 4 is true (append 8), 1 > 4 is false, 6 > 4 is true (append 6), 2 > 4 is false. The result list contains [8, 6], which has a length of 2.
B) Only two elements (8 and 6) exceed 4, not three. C) The filter does not include all elements — only those greater than 4. A) Two elements do satisfy the condition, so the result is not empty.
Students sometimes include 4 itself by mentally reading > as ≥, or they miscount which elements pass the filter without checking each one individually.
For filtering questions, check each element against the condition one at a time. Write a checkmark or X next to each element to keep track.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help