AP CSP
AP Computer Science Principles / All lessons / Big Idea 3: Algorithms and Programming
3Big Idea 3: Algorithms and Programming
AP CSP topic 3.10

Lists

×3

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.

Skill: Code Analysis
list ← [4, 7]
APPEND(list, 9)
INSERT(list, 1, 2)

1. What is the value of list after the code runs?

  1. (A) [4, 7, 9, 2]
  2. (B) [2, 4, 7, 9]
  3. (C) [4, 2, 7, 9]
  4. (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.

Skill: Code Analysis
words ← ["sun", "moon", "star"]
REMOVE(words, 2)
DISPLAY(LENGTH(words))

2. What is displayed?

  1. (A) 1
  2. (B) 2
  3. (C) 3
  4. (D) "moon"
Show answer

(B) 2 Removing index 2 deletes "moon", leaving 2 elements.

Skill: Code Analysis
sum ← 0
FOR EACH v IN [2, 5, 3]
{
   sum ← sum + v
}
DISPLAY(sum)

3. What is displayed?

  1. (A) 3
  2. (B) 5
  3. (C) 10
  4. (D) 30
Show answer

(C) 10 The loop adds every element: 2 + 5 + 3 = 10.

Skill: Algorithms and Program Development

4. A program should count how many elements in a list called temps are below 32. Which code does this?

  1. (A) count ← 0 FOR EACH t IN temps { IF (t < 32) { count ← count + 1 } }
  2. (B) count ← LENGTH(temps)
  3. (C) count ← temps[32]
  4. (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.

Open 3.10 in the interactive course