TutreNews Learn

Tuples, copies and choosing the right structure

Choosing the right structure

Goal: Select list, tuple, dictionary or set for a given task and explain why · 9 min

Choose the structure that matches what you need to do with the data.

needstructurewhy
ordered sequence, duplicates allowed, change itlistindexing, slicing, append, sort
fixed group of values, never changestupleimmutable, usable as dictionary key
look up a value by name or iddictionaryfast lookup by key
unique items, membership test, set algebrasetno duplicates, fast "in"
ordered unique itemslist from sorted(set(...)) or dict keys

Speed in practice (average case):

  • x in my_list checks items one by one: it takes longer the larger the list (O(n)).
  • x in my_set and key in my_dict use hashing and stay fast however large the collection (about O(1)).

A task that repeats "is this item in the collection?" thousands of times should use a set or dictionary, not a list.

Combining structures is normal: a list of dictionaries is a table of records ([{"name": "Ada", "age": 36}, …]); a dictionary of lists groups items under a key; a dictionary with tuple keys can index a grid ({(0, 1): "X"}).

Ask three questions: Do I need order? Do I need uniqueness? Do I look things up by key? The answers point to the structure.

Worked example: Which structure for a spell checker?

  1. We check thousands of words against a dictionary of 100,000 valid words.
  2. Order does not matter, duplicates are pointless, and the main operation is "is it in there?"
  3. → a set of valid words; "word in valid" is fast.
valid = {"cat", "dog", "bird"}
text = ["cat", "cta", "dog"]
print([w for w in text if w not in valid])

Output:

['cta']