AP CSP topic 3.10
Lists
Programs change lists with built-in procedures. In AP pseudocode, APPEND(list, value) adds to the end, INSERT(list, i, value) adds at position i, REMOVE(list, i) deletes position i, and LENGTH(list) gives the number of elements. FOR EACH item IN list visits every element in order, which is called traversing the list. Accessing an index below 1 or above the length is an error.
Lists vocabulary
- Traversal: Visiting each element of a list, usually with a loop.
- APPEND: Adds a value to the end of a list.
- FOR EACH: An AP pseudocode loop that runs once for every element in a list.
- LENGTH: Returns the number of elements in a list.
AP-style practice questions
Try each one, then open the answer. To save your progress, take this quiz in the interactive course.
list ← [4, 7] APPEND(list, 9) INSERT(list, 1, 2)
1. What is the value of list after the code runs?
- (A) [4, 7, 9, 2]
- (B) [2, 4, 7, 9]
- (C) [4, 2, 7, 9]
- (D) [2, 7, 9]
Show answer
(B) [2, 4, 7, 9] APPEND adds 9 to the end: [4, 7, 9]. INSERT at index 1 puts 2 first.
words ← ["sun", "moon", "star"] REMOVE(words, 2) DISPLAY(LENGTH(words))
2. What is displayed?
- (A) 1
- (B) 2
- (C) 3
- (D) "moon"
Show answer
(B) 2 Removing index 2 deletes "moon", leaving 2 elements.
sum ← 0
FOR EACH v IN [2, 5, 3]
{
sum ← sum + v
}
DISPLAY(sum)
3. What is displayed?
- (A) 3
- (B) 5
- (C) 10
- (D) 30
Show answer
(C) 10 The loop adds every element: 2 + 5 + 3 = 10.
4. A program should count how many elements in a list called temps are below 32. Which code does this?
- (A) count ← 0 FOR EACH t IN temps { IF (t < 32) { count ← count + 1 } }
- (B) count ← LENGTH(temps)
- (C) count ← temps[32]
- (D) FOR EACH t IN temps { count ← 0 }
Show answer
(A) count ← 0 FOR EACH t IN temps { IF (t < 32) { count ← count + 1 } } Traversing the list and adding 1 for each match counts the elements below 32.