CAP7004 · Unit 2: Linear data structures
Arrays and dynamic lists
8 practice questions
Key points
- Array index access is O(1)
- Python list is a dynamic array; append is amortized O(1)
- Insert or delete in the middle shifts elements: O(n)
- Slicing copies; build 2D lists with comprehensions
An array stores elements in contiguous memory, so index i is reached directly: a[i] is O(1).
Python's list is a dynamic array of references. When it is full, it allocates a larger block and copies the elements. Growing the capacity geometrically (roughly doubling) makes append amortized O(1): the occasional O(n) copy is spread over many cheap appends. Copying costs for 8 appends starting at capacity 1 total 7 element copies.
| Operation | Cost |
|---|---|
a[i], a[i] = x | O(1) |
append(x), pop() | O(1) amortized / O(1) |
insert(i, x), remove(x), pop(i) | O(n) (shifts elements) |
x in a, index(x) | O(n) |
a[i:j] | O(j - i), makes a new list |
a + b | O(len(a) + len(b)) |
2D arrays: build rows with a comprehension, [[0]*c for _ in range(r)], never [[0]*c]*r.
Exam pitfall: amortized O(1) is not worst-case O(1); one append can still take O(n).
Try two questions
Why is append amortized O(1) in a dynamic array?
- Capacity grows geometrically, so copying is spread over many appends
- Every append copies exactly one element into place
- Python never needs to copy elements when growing
- Lists are stored as chains of linked nodes
Show the answer
A. Rare resize copies average out to a constant cost per append.
x = list(range(10)); y = x[2:5]; y[0] = 99. What is x[2]?
- An error
- 99
- 5
- 2
Show the answer
D. Slicing creates a new list, so changing y does not change x.