Unit 3, Lesson 4 of 5
Brainlag Plus

Lists and 2D lists

GCSE Computer Science, Writing code, 30 minutes

Totals, means, largest and smallest values and linear search on a list, parallel lists, and working along the rows and columns of a 2D list.

Working through a list

Most list tasks are one loop with a variable that remembers something: a total, a count, or the best value so far.

The largest value, without max()

function highest(values)
    best = values[0]
    for i = 1 to values.length - 1
        if values[i] > best then
            best = values[i]
        endif
    next i
    return best
endfunction
print(highest([-4, -9, -2, -7]))
SUBROUTINE highest(values)
    best ← values[0]
    FOR i ← 1 TO LEN(values) - 1
        IF values[i] > best THEN
            best ← values[i]
        ENDIF
    ENDFOR
    RETURN best
ENDSUBROUTINE
OUTPUT highest([-4, -9, -2, -7])
def highest(values):
    best = values[0]
    for i in range(1, len(values)):
        if values[i] > best:
            best = values[i]
    return best
print(highest([-4, -9, -2, -7]))

This prints -2. Starting from the first item, not from 0, matters: if every value is negative, 0 is not in the list at all.

A linear search checks each item in turn and returns its index as soon as it matches. Only after the whole list has been checked does it return -1 for "not found".

  1. Decide what to remember: a total, a count, a best value or an index.
  2. Set it up before the loop.
  3. Loop through every index (or every item).
  4. Update it inside the loop.
  5. Return it after the loop, unless you have found what you were searching for.

The rest of this lesson and its 9 practice questions are in Plus.

Screen 1 of 4, free to read.

  • 9 exam-style questions, marked as you go, each with a worked solution
  • Anything you get wrong is saved to your flashcards