hanegreefs.com/Business Information SystemsBIS
Python 3 · unit 6 of 16

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

StructureOrdered?Mutable?Duplicates?Create withExample
listyesyesyes[ ] or list()[3.5, 7, "Friday", 3.5]
tupleyesnoyes( ) or tuple()("Friday", "Saturday")
setnoyesnoset() or {1, 3, 11}{"hockey", "yoga"}
dictionarykeeps insertion order, no positionsyes (keys must be immutable)keys unique{ } or dict(){"Jun": 95, "Jul": 82}
Common trap{} 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.

OperationExample (letters = ["a", "b", "c"])Effect
appendletters.append("d")adds one element at the end
extend or +letters.extend(["y", "z"])adds every element of another list
insertletters.insert(0, "z")puts an element at a position
removeletters.remove("a")removes the first matching value (ValueError if absent)
popletters.pop(), letters.pop(0)removes and returns the last element, or the one at a position
index, countletters.index("b")position of a value; how often it occurs
sort, sortedletters.sort(), sorted(letters)sort changes the list and returns None; sorted returns a new list
len, min, max, sumsum([8.4, 2, 7])17.4
membership"b" in lettersTrue
Common trapnew = 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.
Worked example

Average and maximum of sales

Monthly sales are [120, 95, 140, 110]. Compute the average and the best month number (1 to 4).

1

Total and count

sum = 465, len = 4
2

Average

465 / 4 = 116.25
3

Best month

max is 140 at index 2, so month 2 + 1 = 3
Answer

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).

OperationOperatorMethoda = {1, 2, 3}, b = {2, 3, 4}
intersection (in both)a & ba.intersection(b){2, 3}
union (in either)a | ba.union(b){1, 2, 3, 4}
difference (in a, not in b)a - ba.difference(b){1}
symmetric difference (in exactly one)a ^ ba.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"])   # He

The 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.

Loading cards
Question
Click, tap or press space to flip
Answer

Multiple choice (9)

Question 1 · Python 3

Which structure fits "the set of countries a customer has visited, without duplicates"?

Why: No duplicates and order does not matter.
Question 2 · Python 3

t = (1, 2, 3); t[0] = 9. What happens?

Why: Item assignment is not allowed on a tuple.
Question 3 · Python 3

a = [3, 1, 2]; b = a.sort(); print(b)

Why: sort returns None.
Question 4 · Python 3

a = [1, 2]; b = a; b.append(3); print(a)

Why: a and b refer to the same list.
Question 5 · Python 3

d = {"a": 1}; d["b"] = 2; d["a"] = 5; print(d)

Why: A new key is added, an existing key is overwritten.
Question 6 · Python 3

len({1, 1, 2, 3, 3})?

Why: A set keeps unique values: 1, 2, 3.
Question 7 · Python 3

Which expression gives the number of items in a dictionary d?

Why: len works on every collection.
Question 8 · Python 3

mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; print(mat[2 // 4][5 % 3])

Why: 2 // 4 = 0 and 5 % 3 = 2: mat[0][2] is 3.
Question 9 · Python 3

Which call removes an element from a set without an error when it is absent?

Why: remove raises KeyError; discard does not.

Exam-style open questions (2)

Open question · Python 3

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.
Open question · Python 3

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.