AP® Computer Science Principles · Big Idea 3 · Topic 3.10

List Indexing and List Procedures

A list stores items in order, each at a numbered index, usually starting at 0. Inserting or removing an item shifts every index after it, so the list stays packed with no gaps.

A list holds items in a fixed order, and each item has an index that tells you its position. Index 0 is the first item, index 1 is the second, and so on. That index is not a permanent label glued to the item. It is just the item's current slot number, and slot numbers have to stay consecutive with no skips.

That is why insert and remove operations ripple through the list. Insert puts a new item at a chosen index and pushes every item that was there, and everything after it, one index higher to make room. Append adds an item at the very end, so nothing else moves and the list's length grows by one. Remove deletes the item at a given index and then slides every later item down one index to close the gap, shrinking the length by one. In all three cases the rule is the same: indices stay consecutive, starting at 0, with no empty slots.

This matters once procedures start looping over a list by index, since a loop that assumes a fixed length or a fixed position for an item will break the moment something is inserted or removed. Tracking length and index carefully here is also what makes later topics, like searching a list or writing a procedure that processes every element, actually work correctly.

Key terms

Index
The numbered position of an item in a list, typically starting at 0.
Insert
An operation that places a new item at a given index and shifts later items one index higher.
Append
An operation that adds an item to the end of a list without moving any existing items.
Remove
An operation that deletes an item at a given index and shifts later items one index lower.
Length
The number of items currently in a list, which changes by one after each append or remove.

Watch it explained

  1. How it worksHow do the insert, append, and remove operations reshape a list and its indices?
  2. Worked exampleTrace inserting 9 at index 2 of the list 4, 6, 8, 10 and then removing index 1.
  3. Worked exampleFind the length of a list after three appends and one removal, starting from length 5.
  4. Common mistakeWhy doesn't removing an element leave a hole in the middle of a list?

Check yourself

Your turn1 of 2
A list starts with length 36. Three elements are appended, and then 3 elements are removed. What is the list's length now?

End of topic.