Lists & Iteration
- Access and modify list elements using 1-based indexing
- Use FOR EACH and indexed loops to process every element
- Trace list operations such as APPEND, INSERT, and REMOVE
Lists store many values
A list holds an ordered collection of values under one name. In AP pseudocode you write one as scores ← [90, 85, 100], and you access an element by its index in square brackets. Crucially, AP pseudocode lists are indexed starting at 1, not 0: scores[1] is 90, scores[2] is 85, and scores[3] is 100. Assigning to an element, like scores[2] ← 88, changes just that slot. LENGTH(scores) gives the number of elements — here 3.
Looping over a list
To process every element you iterate. FOR EACH item IN list { <instructions> } runs the body once per element, with item taking each value in turn — clean when you just need the values. When you need the position, use an indexed loop such as REPEAT LENGTH(list) TIMES with a counter, accessing list[i]. A running variable (an accumulator) is common: start total ← 0, then add each element to total inside the loop to sum the list.
Growing and shrinking lists
AP pseudocode provides list operations. APPEND(list, value) adds a value to the end. INSERT(list, i, value) puts value at index i, shifting later elements one position to the right and increasing the length. REMOVE(list, i) deletes the element at index i, shifting later elements left and decreasing the length. Because insert and remove shift other elements, the indices of items after the change move — a frequent source of tracing errors.
Trace this program. What is displayed?
nums ← [5, 10, 15, 20]
REMOVE(nums, 2)
APPEND(nums, 25)
DISPLAY(nums[3])
- 1.Start: nums = [5, 10, 15, 20]. Indices 1,2,3,4 hold 5,10,15,20.
- 2.
REMOVE(nums, 2)deletes the element at index 2 (the 10) and shifts the rest left: nums = [5, 15, 20]. - 3.
APPEND(nums, 25)adds 25 to the end: nums = [5, 15, 20, 25]. - 4.
nums[3]is the third element, which is now 20.
Given `L ← [7, 14, 21, 28, 35]` in AP pseudocode, what is the value of `L[3]`?
AP pseudocode lists start at index 1, not 0. L[1] is the first element. Mixing this up with 0-based languages you may know is one of the most common exam errors — always count from 1 here.
After this code runs, what does the list `data` contain? `data ← [3, 6, 9]` `INSERT(data, 2, 5)`
On list-tracing questions, redraw the list after every INSERT or REMOVE, because those operations shift the positions of all later elements. Track indices carefully — the exam builds traps out of these shifts.
Answer the 2 checkpoints as you read.
Sign in to save your progress