AP CSP Day 6: List Traversal And Filtering

Key Concepts

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.

Common Trap: Forgetting to initialize the result list before the loop. If the result list does not exist before the loop starts, appending to it causes an error.
Exam Tip: Trace filtering questions by writing out which elements pass the condition. Build the result list step by step rather than trying to predict the answer at a glance.
Big Idea 3: Algorithms & Programming
Cycle 1 • Day 6 Practice • Medium Difficulty
Focus: List Traversal & Filtering

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))
Why This Answer?

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.

Why Not the Others?

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.

Common Mistake
Watch Out!

Students sometimes include 4 itself by mentally reading > as ≥, or they miscount which elements pass the filter without checking each one individually.

AP Exam Tip

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
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.