Understanding
Lists
Learn how lists store ordered collections of data, enabling powerful operations like searching, inserting, and iterating through elements.
What Is a List?
A list is an ordered sequence of elements stored under a single variable name. Each element occupies a specific position, called its index. Lists let you group related data together instead of creating dozens of separate variables.
Why Lists Matter
Without lists, storing 100 student names would require 100 separate variables. Lists make data management scalable and are foundational to every real-world program.
Anatomy of a List
Core Operations
Traversing a List
A traversal visits every element exactly once. You can iterate by index or by element value. Both patterns appear on the AP exam.
FOR i ← 1 TO LENGTH(list)Use \( \text{list}[i] \) to access each element. Best when you need the position.
FOR EACH item IN listitem holds the current value. Simpler when position is not needed.
List vs. Variable
| List | Single Variable | |
|---|---|---|
| Stores | Multiple values | One value |
| Access | By index: \( \text{list}[i] \) | By name: \( x \) |
| Size | Dynamic: grows/shrinks | Fixed: always 1 value |
| Loop-friendly | ✓ Process all at once | ✕ Manual per variable |
| Best for | Collections of related data | Single, independent values |
Working with Lists: Step by Step
Example 1: Building a List
Example 2: Insert and Remove
Example 3: Summing a List
Searching a List
Filtering into a New List
Common Mistakes
List Operations Summary
| Operation | Pseudocode | Effect |
|---|---|---|
| Access | \( \text{list}[i] \) | Returns element at index i |
| Assign | \( \text{list}[i] \leftarrow \text{val} \) | Replaces element at index i |
| Append | \( \text{APPEND}(\text{list}, \text{val}) \) | Adds val to end |
| Insert | \( \text{INSERT}(\text{list}, i, \text{val}) \) | Inserts val at i, shifts right |
| Remove | \( \text{REMOVE}(\text{list}, i) \) | Deletes element at i, shifts left |
| Length | \( \text{LENGTH}(\text{list}) \) | Returns number of elements |
| Traverse | FOR EACH item IN list |
Visits every element once |
Question 1 of 5
Consider the list \( \text{data} \leftarrow [5, 12, 8, 3] \). What is the value of \( \text{data}[3] \)?
Question 2 of 5
What does APPEND(myList, "x") do?
Question 3 of 5
Code segment:
items ← ["a", "b", "c", "d"]
INSERT(items, 2, "z")
REMOVE(items, 4)
What is the final value of items?
Question 4 of 5
Code segment:
nums ← [4, 7, 2, 9, 1]
max ← nums[1]
FOR EACH val IN nums
IF (val > max)
max ← val
What value does max hold after this code runs?
Question 5 of 5
Code segment:
colors ← ["red", "blue", "green"]
result ← []
FOR i ← LENGTH(colors) TO 1 STEP -1
APPEND(result, colors[i])
What does result contain after this code runs?