Lists, tuples, sets and dictionaries
The four built-in data structures: ordered or not, mutable or not, how to create them, the methods you use most, set operations, and nested structures such as a dictionary of lists.
Based on: exercise sessions WPO4 (data structures) and WPO7 (nested data structures), Python building blocks overview · About 70 minutes
Four data structures at a glanceImportant
| Structure | Ordered? | Mutable? | Duplicates? | Create with | Example |
|---|---|---|---|---|---|
| list | yes | yes | yes | [ ] or list() | [3.5, 7, "Friday", 3.5] |
| tuple | yes | no | yes | ( ) or tuple() | ("Friday", "Saturday") |
| set | no | yes | no | set() or {1, 3, 11} | {"hockey", "yoga"} |
| dictionary | keeps insertion order, no positions | yes (keys must be immutable) | keys unique | { } or dict() | {"Jun": 95, "Jul": 82} |
{} creates an empty dictionary, not an empty set. An empty set is set().Choose the structure by the question you ask. A sequence where position matters and that changes: list. A fixed group of values such as a coordinate (50.85, 4.35): tuple. "Is this in it?" and no duplicates: set. Look up a value by a name: dictionary, the Python form of the record type.
ListsImportant
Lists use the same indexing and slicing as strings, but you can change them in place.
| Operation | Example (letters = ["a", "b", "c"]) | Effect |
|---|---|---|
| append | letters.append("d") | adds one element at the end |
| extend or + | letters.extend(["y", "z"]) | adds every element of another list |
| insert | letters.insert(0, "z") | puts an element at a position |
| remove | letters.remove("a") | removes the first matching value (ValueError if absent) |
| pop | letters.pop(), letters.pop(0) | removes and returns the last element, or the one at a position |
| index, count | letters.index("b") | position of a value; how often it occurs |
| sort, sorted | letters.sort(), sorted(letters) | sort changes the list and returns None; sorted returns a new list |
| len, min, max, sum | sum([8.4, 2, 7]) | 17.4 |
| membership | "b" in letters | True |
new = letters.sort() leaves new equal to None. And b = a does not copy a list: both names refer to the same list, so a change through b is visible through a. Use b = a[:] or list(a) for a copy.Average and maximum of sales
Monthly sales are [120, 95, 140, 110]. Compute the average and the best month number (1 to 4).
Total and count
Average
Best month
Average 116.25 and best month 3. Indexes start at 0, months at 1: add one.
TuplesNeutral
A tuple is an ordered, immutable sequence: indexing, slicing, len, in and count work, but append, remove or item assignment give an error (AttributeError or TypeError). Tuples are useful for values that belong together and must not change, and they can be unpacked: lat, lon = (50.85, 4.35). A tuple with one element needs a comma: (5,).
Sets and set operationsImportant
A set holds each value only once and has no order, so there is no indexing. set(["Germany", "Belgium", "Germany"]) keeps two countries. Use add, remove (error if absent) and discard (no error).
| Operation | Operator | Method | a = {1, 2, 3}, b = {2, 3, 4} |
|---|---|---|---|
| intersection (in both) | a & b | a.intersection(b) | {2, 3} |
| union (in either) | a | b | a.union(b) | {1, 2, 3, 4} |
| difference (in a, not in b) | a - b | a.difference(b) | {1} |
| symmetric difference (in exactly one) | a ^ b | a.symmetric_difference(b) | {1, 4} |
Because sets have no order, printing them can show the elements in any order. In exam answers and tests, use sorted(a & b) to get a list in a fixed order.
DictionariesImportant
A dictionary maps keys to values. Look up with d[key] (KeyError if the key is missing) or d.get(key, default) (no error). Assigning to a new key adds it; assigning to an existing key replaces the value.
stock = {"pen": 120, "paper": 40}
stock["ink"] = 15 # add
stock["pen"] -= 20 # change
print(stock.get("glue", 0)) # 0, no error
for item, qty in stock.items():
print(item, qty)keys(), values() and items() give the keys, the values and the (key, value) pairs. A counting pattern comes back in many exercises: counts[word] = counts.get(word, 0) + 1 for every word.
Nested data structuresNeutral
Structures can contain other structures: a list of lists (a matrix), a list of tuples, a dictionary whose values are lists or dictionaries. Read the access path from left to right.
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(mat[1][2]) # row 1, column 2: 6
shops = {"Brussels": [120, 95], "Ghent": [80, 110]}
print(sum(shops["Ghent"])) # 190
elements = {"helium": {"number": 2, "symbol": "He"}}
print(elements["helium"]["symbol"]) # HeThe exercise sessions use such structures for profits per shop, names, a tennis tournament and a Morse code dictionary. The method is always the same: loop over the outer structure, then work on the inner one.
Key takeaways
- List: ordered and mutable. Tuple: ordered and immutable. Set: unordered, no duplicates. Dictionary: key to value.
- {} is an empty dictionary; an empty set is set().
- sort() changes the list and returns None; sorted() returns a new list.
- Set operators: & intersection, | union, - difference, ^ symmetric difference.
- d[key] raises KeyError for a missing key; d.get(key, default) does not.
All cards known
Reset the progress or pick another unit to keep practising.
Multiple choice (9)
Which structure fits "the set of countries a customer has visited, without duplicates"?
t = (1, 2, 3); t[0] = 9. What happens?
a = [3, 1, 2]; b = a.sort(); print(b)
a = [1, 2]; b = a; b.append(3); print(a)
d = {"a": 1}; d["b"] = 2; d["a"] = 5; print(d)
len({1, 1, 2, 3, 3})?
Which expression gives the number of items in a dictionary d?
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; print(mat[2 // 4][5 % 3])
Which call removes an element from a set without an error when it is absent?
Exam-style open questions (2)
Choose a data structure
For each case choose list, tuple, set or dictionary and explain: (a) the days of the working week, (b) the prices of products by product code, (c) the queue of orders to handle, (d) the distinct cities of the customers.
Show a model answer outline
- (a) tuple: fixed and ordered.
- (b) dictionary: look up by code.
- (c) list: ordered, changes (append, pop(0)).
- (d) set: unique values, order irrelevant.
Word counter
Write a function that receives a sentence and returns a dictionary with how often each word appears, ignoring capitals. Explain each step.
Show a model answer outline
- lower() then split() into words.
- Empty dictionary; for each word counts[w] = counts.get(w, 0) + 1.
- Return the dictionary.
- Example: "the cat and the dog" gives the: 2, cat: 1, and: 1, dog: 1.
LabCoding lab: working with data structures
Each exercise is a function. Your function is called with several test values and the results are compared with the expected ones.
LabSet operations explorer
Separate the values with commas. Duplicates disappear as soon as a set is made.