hayaliv

hayaliv / Hi! Python / Level 0

Lists, tuples, dicts and sets

Lists change, tuples do not, dicts look things up by key, and sets keep unique items.

Hi! Python · Level 0: Python core · Checked against the Python 3.12 documentation · Updated 2026-10-17

Think of it like this

A library has shelves (lists), sealed boxes (tuples), a card catalogue (dicts) and a guest list with no repeated names (sets). You can add a book to a shelf, but you cannot swap a book inside a sealed box.

Where the analogy stops being true. A real catalogue can hold two cards with the same title, but a dict key can appear only once.

What to know

Example

labels = ["meeting_request", "not_interested", "meeting_request"]
labels.append("question")
print(labels[0], labels[-1], len(labels))
pair = ("reply_17", "not_interested")
print(pair[1])
counts = {"meeting_request": 2, "not_interested": 1}
print(counts["meeting_request"])
print(counts.get("question"))
print(counts.get("question", 0))
print("question" in counts)
unique = set(labels)
print(len(unique), sorted(unique))

It prints:

meeting_request question 4
not_interested
2
None
0
False
3 ['meeting_request', 'not_interested', 'question']

Predict, then check

1. What does this print?

a = ["x"]
b = a
b.append("y")
print(a)
Show the answer
['x', 'y']

Both names point at the same list. Changing it through b changes what a sees.

2. What does this print?

d = {"a": 1}
print(d.get("b"), d.get("b", 0), "a" in d)
Show the answer
None 0 True

get() gives None or your default for a missing key, and in checks the keys.

3. What does this print?

t = (1, 2)
try:
    t[0] = 9
except TypeError:
    print("tuples cannot change")
Show the answer
tuples cannot change

Tuples are immutable, so assigning to an item raises TypeError, which the except branch catches.

Try it

Write count_labels(labels) that takes a list of label strings and returns a dict mapping each label to how many times it appears.

def count_labels(labels):
    return {}
Show a solution
def count_labels(labels):
    counts = {}
    for label in labels:
        counts[label] = counts.get(label, 0) + 1
    return counts

Common mistake

{} makes an empty dict, not an empty set. To make an empty set, use set().

In a small-language-model project

In a fine-tuning project you usually keep replies in a list, labels in a set to see which classes exist, and label counts in a dict to check whether your classes are balanced.

Sources

Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).

Step through this lesson in the Hi! Python desktop

← Strings and f-stringsControl flow →