CAP7004 · Unit 1: Python foundations and analysis
Built-in Python data structures and their costs
8 practice questions
Key points
- list/dict/set/tuple differ in order, mutability and duplicates
- dict and set lookups are O(1) on average, list search is O(n)
- pop(0) and insert(0) on a list cost O(n)
- Assignment shares references; copy explicitly
Python's built-ins are the data structures you use most.
| Type | Ordered | Mutable | Duplicates | Typical use |
|---|---|---|---|---|
| list | Yes | Yes | Yes | Sequence, stack |
| tuple | Yes | No | Yes | Fixed records, dict keys |
| dict | Insertion order (3.7+) | Yes | Unique keys | Key-value lookup |
| set | No | Yes | No | Membership, uniqueness |
Average costs (n = size):
- list: index
a[i]O(1),appendamortized O(1),pop()O(1),pop(0)andinsert(0, x)O(n),x in aO(n). - dict and set: lookup, insert, delete average O(1); worst case O(n) with many collisions.
- Slicing copies:
a[i:j]costs O(j - i).
Pitfalls: b = a copies the reference, not the list. [[0]*3]*3 repeats the same inner list three times, so changing one row changes all. list.sort() sorts in place and returns None; sorted() returns a new list. A mutable default argument such as def f(x, l=[]) is created once and shared between calls.
Try two questions
After a = [1, 2, 3]; b = a; b.append(4), what is a?
- [1, 2, 3]
- [4, 1, 2, 3]
- [1, 2, 3, 4]
- An error is raised
Show the answer
C. b and a refer to the same list object, so the change is visible through both names.
def f(x, l=[]): l.append(x); return l. After f(1), the call f(2) returns:
- [2, 1]
- [1, 2]
- [1]
- [2]
Show the answer
B. The default list is created once at definition time and reused across calls.