Lists & Loops

Beginner · IntermediateAbout 12 minProgramming & algorithms

Need to work with 30 test scores? You don't want 30 variables — or 30 copies of the same code.

One Name, Many Values

A list keeps many values together under one name. Each item has a position called its index. In this pseudocode, the first item is at index 1:

scores ← [72, 95, 88, 61]
DISPLAY(scores[1])
DISPLAY(scores[3])
DISPLAY(LENGTH(scores))

That displays 72 (the first item), 88 (the third) and 4 (how many items there are). Lists can also change while a program runs:

  • APPEND(scores, 80) adds 80 to the end.
  • INSERT(scores, 2, 50) puts 50 at index 2 and shifts the rest along.
  • REMOVE(scores, 1) takes out the first item and shifts the rest back.

Some languages count from 0 instead of 1 — always check which one you're using. Using an index that doesn't exist, like scores[5] in a list of four, is an error.

Loops: Repeat Without Rewriting

A loop runs the same steps again and again. There are three kinds you'll see:

  • REPEAT n TIMES — when you know how many times.
  • REPEAT UNTIL (condition) — when you stop once something becomes true.
  • FOR EACH item IN list — once for every item in a list, in order.

Going through a list one item at a time is called traversing the list.

Try it yourself

scores

Patterns Worth Knowing

Most list programs are one of a few patterns:

  • Total — start at 0 and add each item.
  • Largest or smallest — remember the best so far, and replace it when you find a better one.
  • Count — start at 0 and add 1 whenever an item matches a condition.
  • Filter — build a new list containing only the items you want.

Practice reading these with Pseudocode Practice, or see how lists get searched in Binary Search.

Check your understanding

5 quick questions. Pick one answer for each — you'll see why straight away.

  1. scores ← [70, 85, 90]. In this pseudocode, what is scores[1]?

  2. What does LENGTH(scores) give for scores ← [70, 85, 90, 60]?

  3. Why use a loop to add up 100 test scores, instead of 100 separate lines?

  4. total ← 0, then FOR EACH n IN [2, 4, 6] { total ← total + n }. What is total at the end?

  5. Which loop is the best fit for "keep asking for a password until it's correct"?