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.
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
- A list is mutable, so you can add to it after it is created.
- A tuple is immutable. Its items cannot be reassigned.
- Lists and tuples are indexed by position, starting at 0.
- A dict is indexed by keys, and the keys are unique within one dictionary.
- dict.get(key) returns None instead of raising an error when the key is missing, and you can pass your own default.
- The in operator on a dict checks keys. On a list it checks items.
- A set holds distinct items, so converting a list to a set removes duplicates.
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 Trueget() 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 changeTuples 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 countsCommon 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).
Lists are mutable sequences, typically used to store collections of homogeneous items
docs.python.org/3.12/library/stdtypes.html — Lists are mutable sequences.Tuples are immutable sequences, typically used to store collections of heterogeneous data
docs.python.org/3.12/library/stdtypes.html — Tuples are immutable sequences.dictionaries are indexed by keys , which can be any immutable type
docs.python.org/3.12/tutorial/datastructures.html — Dictionaries are indexed by keys.with the requirement that the keys are unique (within one dictionary).
docs.python.org/3.12/tutorial/datastructures.html — Dict keys are unique.If default is not given, it defaults to None , so that this method never raises a KeyError .
docs.python.org/3.12/library/stdtypes.html — dict.get never raises KeyError and defaults to None.True if an item of s is equal to x , else False
docs.python.org/3.12/library/stdtypes.html — x in s tests whether an item of s equals x.A set is an unordered collection with no duplicate elements.
docs.python.org/3.12/tutorial/datastructures.html — A set has no duplicate elements.to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary
docs.python.org/3.12/tutorial/datastructures.html — An empty set needs set(), not {}.multiple names (in multiple scopes) can be bound to the same object.
docs.python.org/3.12/tutorial/classes.html — Two names can be bound to one object (aliasing).i th item of s , origin 0
docs.python.org/3.12/library/stdtypes.html — Sequences are indexed from 0.Return True if d has a key key , else False .
docs.python.org/3.12/library/stdtypes.html — key in d tests the keys of a dict.