AP CSP Day 64: List Operations: Insert and Remove Index Shifting | Cycle 3
Share
In AP CSP pseudocode, lists are 1-indexed. INSERT shifts existing elements right. REMOVE shifts elements left to fill the gap. Performing multiple inserts and removes in sequence requires re-evaluating indices after each operation because positions change.
Study the Concept First (Optional) Click to expand ▼
Index Shifting After Insert and Remove
INSERT Behavior
INSERT(list, i, value) places the new value at index i and shifts everything from index i onward to the right. The list length increases by 1.
REMOVE Behavior
REMOVE(list, i) deletes the element at index i and shifts everything after it to the left. The list length decreases by 1.
Practice Question
Consider the following code segment.
list ← ["P", "Q", "R", "S", "T"]
REMOVE(list, 2)
INSERT(list, 3, "X")
REMOVE(list, 1)What are the contents of list after the code segment executes?
Step 1: Start with ["P", "Q", "R", "S", "T"]. REMOVE(list, 2) removes "Q". List becomes ["P", "R", "S", "T"]. Step 2: INSERT(list, 3, "X") inserts "X" at index 3, shifting "S" and "T" right. List becomes ["P", "R", "X", "S", "T"]. Step 3: REMOVE(list, 1) removes "P". List becomes ["R", "X", "S", "T"].
A) Would occur if REMOVE(list, 2) removed "R" instead of "Q" (wrong element). B) Assumes INSERT placed "X" after "S" rather than at index 3. C) Keeps "P" in the list, missing the final REMOVE operation.
Students trace the first operation correctly but forget to re-index before the second operation. After removing index 2, what was at index 3 is now at index 2.
Write out the list state after EACH operation. Do not try to compute the final state in your head. One wrong index cascades through all subsequent operations.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help