Grade 9 Computer Science · Choosing a data structure

The question that settles it

Not “what is the data”, but “what shall I ask of it”.

A list of names? Not necessarily

You have students’ names, so a list — right? Not necessarily. If all you will want to know is whether a certain student is in the class, there is a structure that answers that at once — and it does not even keep the order in which you put the names in.

The first urge in choosing a structure is to look at the data: these are names, so a list of names. That is the wrong way, and it leads to a wrong choice in about half the cases. The right way looks at something else entirely.

The choice follows from the question you will ask, not the kind of data.
The question you will askThe structure
What is the next item in orderA list
What is this name’s valueA dictionary
Does this item existA set
names = ["Ana", "Ben", "Ana"]     # order, duplicates kept
ages = {"Ana": 14, "Ben": 15}     # reached by name
seen = {"Ana", "Ben"}             # membership only

print(len(names), len(ages), len(seen))

The set — the new structure here

A list and a dictionary are already familiar; the set is new, and it is simple: a collection of items with no values, no order, and no duplicates. The last two properties are not limitations but exactly what is bought. No duplicates means adding an item already there does nothing — and that is the simplest way to remove duplicates from data. And no order allows “does it exist” to be answered in a time independent of the size, exactly like a dictionary. A set is, in that sense, a dictionary that gave up the values and kept only the keys.

Example 1 — the same data, three choices

  1. The data is names, in all three cases.
  2. For a question about order — a list.
  3. For a question about a name’s value — a dictionary.
  4. For a question about existence alone — a set.

Example 2 — a set removes duplicates

  1. An item already there is added.
  2. The set does not change at all.
  3. In the end it holds each item once.
  4. And that is the simplest way to do it.
The data is the same in every row; only the question changes.