AP® Computer Science Principles · Big Idea 3 · Topic 3.2
Lists, Indices, and Strings
A list stores many values under one name, and an index is the position number that picks out exactly one of those values. In this pseudocode, indexing starts at 1, so the first item sits at index 1, not 0.
A list bundles many related values into a single named collection, so a program can work with hundreds of items using one name and a changing index instead of hundreds of separate variable names. This matters the moment you want to repeat an action over many values: a loop can walk through a list by index, touching every element with a few lines of code, something impossible if every value needed its own name.
An index is just the position of an item within the ordered sequence. In this pseudocode, indexing is 1 based: the first element lives at index 1, the second at index 2, and so on, up through index n for a list of n items. To read or change one value, a program names the list and gives an index, and that pair picks out exactly one element. Asking for an index that does not exist, like index 9 in a 5 item list, is an error, not a safe fallback. The list does not resize itself, return an empty value, or clamp to the last item. It simply fails, because that position names nothing.
Lists set up the next step in this unit: procedures that take a list as input and loop over its indices to search, sum, or sort its contents. Every one of those algorithms depends on knowing exactly where each element lives, which is the whole job of an index.
Key terms
- list
- An ordered collection of values stored under a single name.
- index
- A number giving the position of one element within a list.
- 1-based indexing
- A numbering scheme where the first element of a list sits at index 1, not 0.
- out of bounds
- An index that does not correspond to any element in the list, which causes an error.
Watch it explained
- How it worksHow does an index pick exactly one element out of an ordered sequence?
- Worked exampleFind the value at index 3 of the list 12, 7, 9, 20, 5 under one based indexing.
- Common mistakeWhy doesn't the first element of an AP pseudocode list live at index 0?
- Going furtherWhat happens when a program asks for the element at index 9 of a list holding 5 items?
Check yourself
End of topic.