Lists and Arrays

⏱ 8 min✏️ Quiz at the end

Thirty Variables Is Twenty-Nine Too Many

A variable holds one value. Now store the test scores of a class of thirty. Thirty variables β€” score1, score2, … score30? Then adding them up takes a thirty-line sum, finding the highest takes a thirty-way comparison, and student thirty-one breaks everything.

The fix is a container built for the job. A list (called an array in many languages) stores many values in order, under one name:

scores ← [12, 7, 19, 3, 15]

One name, five values β€” or five million. The values keep their order, and each has a numbered position.

Indexing: Finding Item Number i

Each position in a list has an index, and here is the famous quirk: in most programming languages, counting starts at zero.

index:    0    1    2    3    4
scores: [12,   7,  19,   3,  15]

So scores[0] is 12 β€” the first item β€” and scores[2] is 19, the third. Zero-based counting feels odd for a week and then becomes second nature. You can read and overwrite by index:

OUTPUT scores[4]      ← prints 15
scores[1] ← 8         ← the 7 becomes an 8

One boundary demands respect: a list of five items has indices 0 to 4. Ask for scores[5] and you are reaching past the end β€” an out-of-bounds error, and in most languages a crash. Note the pattern: last index = length βˆ’ 1. Forgetting that "βˆ’ 1" is the same off-by-one error that haunts loops β€” the two bugs are cousins.

Lists and Loops: A Perfect Partnership

The real power switches on when lists meet loops. To total the scores, whether five or five million:

total ← 0
FOR i ← 0 TO length(scores) βˆ’ 1
    total ← total + scores[i]
NEXT
OUTPUT total

The loop counter doubles as the index, visiting every item in turn. Compare the doomed thirty-variable version: this code does not change when the class grows. That is the deep reason lists exist β€” they let one piece of logic scale to any amount of data.

Every list-processing task you will ever meet is a variation on this loop pattern:

  • Sum or average β€” accumulate as you visit
  • Find the largest β€” keep a biggest variable, challenge it with each item
  • Count matches β€” add 1 whenever the condition holds
  • Search β€” stop when you find the target (that is exactly linear search)

And of course sorting algorithms β€” bubble sort's neighbour-swapping is nothing but index work: comparing scores[i] with scores[i+1].

Lists Hold Anything

Numbers, text, Booleans β€” anything a variable can hold, a list can hold many of:

names ← ["Aisha", "Ben", "Carlos"]
answers ← [true, false, true, true]

Two related lists can even work as a team: names[i] scored scores[i] β€” the same index links them. (Real languages offer fancier structures for that job β€” tables of records β€” but paired lists are the honest beginning.)

Try It Yourself

In pseudocode, given temps ← [18, 21, 16, 24, 19]:

  1. Output the temperature at index 3 (predict it first!)
  2. Write a loop that finds the hottest value
  3. Write a loop that counts days above 18
  4. Trace your hottest-day loop β€” does it still work if the list has just one item? None?

Worked Example β€” Finding the Highest Score, Step by Step

"Find the largest value" is one of the most common list tasks, and it is worth tracing carefully once so the pattern becomes automatic. Given scores ← [12, 7, 19, 3, 15]:

biggest ← scores[0]
FOR i ← 1 TO length(scores) βˆ’ 1
    IF scores[i] > biggest THEN
        biggest ← scores[i]
    ENDIF
NEXT
OUTPUT biggest
iscores[i]scores[i] > biggest?biggest
(start)12
177 > 12? No12
21919 > 12? Yes19
333 > 19? No19
41515 > 19? No19

The output is 19. Notice the design decision at the very top: biggest starts as scores[0], not 0. Starting at 0 would silently break the algorithm the moment every score was negative β€” exactly the boundary-case trap explored in testing programs and trace tables. Starting from the list's own first item, rather than an assumed value, is the safer habit.

Two-Dimensional Lists: A Grid of Lists

Sometimes data naturally forms a grid rather than a single row β€” a game board, a spreadsheet, an image's pixels. The natural extension is a list of lists: each item of the outer list is itself a list.

grid ← [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]

OUTPUT grid[1][2]     ← the row at index 1 is [4, 5, 6]; item at index 2 of THAT row is 6

Visiting every cell of a grid needs a loop inside a loop β€” one loop for rows, one for columns within each row β€” which is exactly why lists and nested loops are introduced side by side in this course: one is the data, the other is how you walk across it.

Key Words

  • List / array β€” an ordered collection of values under one name
  • Index β€” an item's numbered position, usually counted from 0
  • Out-of-bounds β€” using an index past the end of the list; a classic crash
  • length β€” the number of items; the last index is length βˆ’ 1
  • Traversal β€” visiting every item with a loop