impera Open Impera

AP Computer Science Principles · Algorithms and programming

Lists

1What lists are

A list is an ordered sequence of elements, stored under one name. In AP pseudocode:

colours ← ["red", "green", "blue"]
  • Elements are accessed by index, starting at 1: colours[1] is "red".
  • LENGTH(colours) is 3.
  • Accessing an index less than 1 or greater than the length causes an error, and the program stops.

Lists are a data abstraction: one name manages many values, so programs can handle any number of items without a separate variable for each.

Check yourself

For nums ← [8, 3, 5], what is nums[2]?

  • 5

  • 8

  • 3

  • An error

Show the answer

3

Index starts at 1.

2List operations

AP pseudocode list procedures:

  • INSERT(list, i, value): inserts at index i, shifting later elements right.
  • APPEND(list, value): adds to the end.
  • REMOVE(list, i): removes the element at index i, shifting later elements left.
  • list[i] ← value: replaces the element at index i.
Worked example

start with L ← [4, 9].

  1. APPEND(L, 2) → [4, 9, 2]
  2. INSERT(L, 1, 7) → [7, 4, 9, 2]
  3. REMOVE(L, 3) → [7, 4, 2]
  4. L[2] ← 0 → [7, 0, 2]

List operations step by step (AP lists start at index 1); green marks the changed element

Check yourself

Starting with L ← [1, 2, 3], what is L after REMOVE(L, 1)?

  • [3]

  • [2, 3]

  • [1, 3]

  • [1, 2]

Show the answer

[2, 3]

Removes the first element.

3Traversing lists

Traversal visits each element in turn, with either:

FOR EACH item IN list
{
   <block>
}

or an index loop using REPEAT and a counter.

Standard algorithms using traversal:

  • sum or average of the elements;
  • finding the minimum or maximum;
  • counting elements that meet a condition;
  • linear search for a value.
Worked example

find the largest value.

max ← nums[1]
FOR EACH n IN nums
{
   IF (n > max)
   {
      max ← n
   }
}
Check yourself

Why start max at nums[1] rather than 0?

  • If all values are negative, 0 would be wrong

  • Lists cannot contain the value 0 at all

  • It is faster than starting at 0

  • The loop starts at index 2 instead

Show the answer

If all values are negative, 0 would be wrong

Use a real element.

4Why lists manage complexity

Without lists, a program storing 100 test scores would need 100 variables and 100 separate statements to total them. With a list, one loop handles any number of scores, and the code does not change when more scores are added.

This manages complexity: the program is shorter, easier to read and easier to change.

Check yourself

How does using a list manage complexity?

  • It makes programs longer and harder to follow

  • It stores only one value under a single name

  • One name and one loop can handle any number of values

  • It removes the need for any loops in the program

Show the answer

One name and one loop can handle any number of values

Generalises the code.

5Going deeper: list operations in AP pseudocode, traversal algorithms and tracing

A list is an ordered sequence of elements. Each element is identified by its index.

In AP pseudocode, indices start at 1, not 0. For nums ← [10, 20, 30], nums[1] is 10 and nums[3] is 30. Using an index less than 1 or greater than the length causes an error and the program stops.

The operations on the reference sheet

  • aList[i]: the element at index i.
  • aList[i] ← value: replace that element.
  • INSERT(aList, i, value): put value at index i; elements at i and beyond shift right; the length grows by 1.
  • APPEND(aList, value): add to the end.
  • REMOVE(aList, i): delete the element at index i; later elements shift left; the length shrinks by 1.
  • LENGTH(aList): the number of elements.
  • FOR EACH item IN aList { }: item takes each element's value in turn, first to last.

Worked example (trace):

letters ← ["a", "b", "c"]
INSERT(letters, 2, "z")
APPEND(letters, "q")
REMOVE(letters, 1)
letters[2] ← "m"
DISPLAY(letters)
  1. Start: [a, b, c].
  2. INSERT at 2: [a, z, b, c].
  3. APPEND: [a, z, b, c, q].
  4. REMOVE index 1: [z, b, c, q].
  5. Replace index 2: [z, m, c, q].

Why use a list? One name for many values is a data abstraction: it manages complexity.

  • The program does not need a separate variable for each value (score1, score2, …).
  • The same code works whether there are 5 elements or 5000.
  • Adding another value needs no new code.

Traversal: visiting every element, in whole or in part.

Sum and average

total ← 0
FOR EACH n IN nums
{
    total ← total + n
}
average ← total / LENGTH(nums)

Maximum

largest ← nums[1]
FOR EACH n IN nums
{
    IF (n > largest)
    {
        largest ← n
    }
}

Start from the first element, not from 0: all the values might be negative.

Linear search

found ← false
FOR EACH n IN nums
{
    IF (n = target)
    {
        found ← true
    }
}

Traversal by index, when the position matters:

i ← 1
REPEAT LENGTH(nums) TIMES
{
    DISPLAY(nums[i])
    i ← i + 1
}

Worked example (trace with indices): what is displayed?

vals ← [4, 9, 2, 7]
k ← 1
REPEAT 3 TIMES
{
    vals[k + 1] ← vals[k] + vals[k + 1]
    k ← k + 1
}
DISPLAY(vals)
  1. k = 1: vals[2] = 4 + 9 = 13: [4, 13, 2, 7].
  2. k = 2: vals[3] = 13 + 2 = 15: [4, 13, 15, 7].
  3. k = 3: vals[4] = 15 + 7 = 22: [4, 13, 15, 22].
  4. Displays [4, 13, 15, 22]: running totals.

FOR EACH gives a copy of each element. Assigning to the loop variable does not change the list; to change elements, use indices.

Assigning a list: bList ← aList gives bList a copy of the list (in this pseudocode).

Common list algorithms to recognize: counting elements that meet a condition; building a new list of selected or transformed elements; finding the position of an element; checking whether the list is in order; swapping two elements (with a temporary variable).

Lists of strings, and strings as sequences: a string behaves much like a list of characters; many languages let you traverse it the same way.

Common mistakes

  • Starting from index 0.
  • Forgetting that INSERT and REMOVE shift the later elements.
  • Using an index beyond LENGTH.
  • Removing elements while stepping forward by index, so that one is skipped.
  • Initializing a maximum to 0.
  • Expecting FOR EACH to change the list by assigning to the loop variable.
Check yourself

After data ← [5, 10, 15, 20] and REMOVE(data, 2), what is data[2]?

  • 10

  • 15

  • 5

  • 20

Show the answer

15

The 10 is removed and the later elements shift left: [5, 15, 20].

6For top marks

  • Use 1-based indices in AP pseudocode, and remember the last element is list[LENGTH(list)].
  • Track how INSERT and REMOVE shift indices of later elements.
  • Explain list use in terms of managing complexity (the Create task asks for this).
  • Initialise accumulators before traversing.
Example

"Storing the quiz questions in a list means adding a new question only requires adding one element, rather than rewriting the code that displays questions."

Check yourself

What is the last element of a non-empty list L?

  • L[LENGTH(L) − 1]

  • L[0]

  • L[LENGTH(L) + 1]

  • L[LENGTH(L)]

Show the answer

L[LENGTH(L)]

1-based indexing.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera