AP CSP Day 57: List Traversal & Filtering | Cycle 2
Share
In-place mutation during traversal is a subtle bug where a loop removes or inserts elements into the list being iterated, causing the traversal to skip elements or process the same element twice. The correct approach is to build a new result list during traversal rather than modifying the original list in the loop. AP CSP Cycle 2 list review questions present traversal algorithms that appear to filter correctly but contain an in-place mutation that causes elements to be skipped. Identifying the specific element that is incorrectly included or excluded demonstrates advanced list algorithm analysis.
📚 Study the Concept First (Optional) Click to expand ▼
In-Place Mutation During Traversal
Why Mutating While Iterating Is Dangerous
When you remove or insert elements from a list while a FOR EACH loop is traversing it, the loop's position shifts relative to the modified list. Elements may be skipped (if an element before the current position is removed) or processed twice (if an element is inserted).
Correct Approach
The safe pattern is to traverse the original list and build a new result list. The original list is never modified during traversal. After the loop, the result list contains exactly the correct filtered elements.
Practice Question
What is displayed after the following code runs?
temps ← [72, 85, 68, 91, 77, 83, 69]
hotDays ← 0
mildDays ← 0
FOR EACH t IN temps
{
IF t ≥ 80
{
hotDays ← hotDays + 1
}
ELSE
{
IF t ≥ 70
{
mildDays ← mildDays + 1
}
}
}
DISPLAY(hotDays)
DISPLAY(mildDays)Trace each temperature: 72 (<80, ≥70: mild), 85 (≥80: hot), 68 (<80, <70: neither), 91 (≥80: hot), 77 (<80, ≥70: mild), 83 (≥80: hot), 69 (<80, <70: neither). Hot=3, Mild=2.
B) Only 2 temperatures fall in the mild range (70-79), not 4. C) Three temperatures are ≥80, not two. A) The counts are 3 and 2, not 4 and 3.
Students count temperatures ≥70 for mildDays without first checking if they are ≥80 (which would route to hotDays instead). In an IF/ELSE, temperatures ≥80 go to hot and never reach the mild check.
In nested IF/ELSE structures, elements that satisfy the outer condition never reach the inner condition. Track each element through the exact path it takes in the conditional logic.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help