Lesson 9 of 10
You now have four containers. Picking the right one makes code shorter, faster, and clearer — picking the wrong one makes you write loops you didn't need.
The comparison
| | List | Tuple | Dictionary | Set |
| --- | --- | --- | --- | --- |
| Syntax | [1, 2] | (1, 2) | {"a": 1} | {1, 2} |
| Ordered | yes | yes | yes (insertion) | no |
| Changeable | yes | no | yes | yes |
| Duplicates | yes | yes | keys unique | no |
| Look up by | index | index | key | — |
The decision, in four questions
1. Do you look things up by name? Use a dictionary. Storing a user's email, age, and
city? user["email"] beats remembering user[2] every time.
2. Do you only care whether something is present, with no duplicates? Use a set. Tags, allowed usernames, "which pages has this visitor seen" — all sets.
3. Should it never change? Use a tuple. A coordinate, an RGB colour, a fixed pair of values returned together.
4. Otherwise? Use a list. Ordered, changeable, allows duplicates — the sensible default when nothing above applies.
Picking wrong: a worked example
Say you want to count how many times each word appears. With a list:
words = ["a", "b", "a", "c", "b", "a"]
unique_words = []
counts = []
for word in words:
if word in unique_words:
counts[unique_words.index(word)] += 1
else:
unique_words.append(word)
counts.append(1)
print(unique_words)
print(counts)
Two parallel lists you have to keep in sync, plus an .index() scan on every word. Now with a
dictionary:
words = ["a", "b", "a", "c", "b", "a"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
Three lines, nothing to keep in sync, and faster. The data structure did the work.
Combining them
Most real programs use several together. A list of dictionaries for records, a set for fast membership checks, tuples for fixed pairs:
people = [
{"name": "Ada", "tags": {"python", "math"}},
{"name": "Grace", "tags": {"compilers"}},
]
for person in people:
if "python" in person["tags"]:
print(person["name"])
Try it yourself
Count the words using a dictionary, then print the count for "a" and the number of unique
words.
Checkpoint
- Look up by name → dictionary. Uniqueness or membership → set.
- Must not change → tuple. Anything else → list.
- The right structure removes loops rather than adding them.
- Real programs nest and combine all four.
Questions about this lesson
Log in to ask a question.