B2.2.1 Static vs dynamic data structures
SL + HLCommand term: Compare1. What happens in memory?
ShelfWise must store the books on the "New arrivals" shelf. Step through how memory is allocated by a static array, a dynamic array and a linked list, and what happens when the shelf gets one more book.
2. Memory simulator
Each square is one memory cell with an address. Grey cells already belong to other programs. Choose a structure, then add, insert and remove books. Watch where memory is allocated, what resizing costs, and how many cells are wasted or used for pointers.
3. Growth race: the cost of adding items
Add books one at a time. Each bar is the work for one append (cells written or copied). The dynamic array doubles its capacity when full.
4. Static or dynamic? ShelfWise design choices
For each piece of ShelfWise data, choose the more suitable kind of structure. Think: is the maximum size known and fixed?
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Static or dynamic?
Which kind of data structure does each statement describe? Streaks of 3+ score double.
7. 45-second speed round: true or false?
Part A: design decisions
Part B: code
Expected output (the byte sizes depend on your Python version)
Python's list is a dynamic array: it reserves spare capacity and only reallocates (and copies) when that runs out. The jumps in bytes are those reallocations. A fixed-size list such as [0] * 7 plus a range check behaves like a static array.
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: A fixed-size array
A static array has a fixed capacity. Simulate one with a list created as [None] * capacity and a separate count. Write add(arr, count, item) that stores the item at position count and returns the new count, or prints "full" and returns the same count when there is no space.
Starter file (write your code where it says pass # your code here):
def add(arr, count, item):
pass # your code here
# ---- tests ----
shelf = [None] * 3
n = 0
for book in ["Dune", "Emma", "Holes", "Kim"]:
n = add(shelf, n, book)
print(shelf, n)
Expected output when your code is correct:
full ['Dune', 'Emma', 'Holes'] 3
Hint
count changes.Model solution
def add(arr, count, item):
if count == len(arr):
print("full")
return count
arr[count] = item
return count + 1
# ---- tests ----
shelf = [None] * 3
n = 0
for book in ["Dune", "Emma", "Holes", "Kim"]:
n = add(shelf, n, book)
print(shelf, n)
Task 2: How expensive is growing?
A dynamic array doubles its capacity when it is full, copying every element to the new space. Write simulate(n, start_capacity) that simulates n appends and returns (final_capacity, resizes, copies). Then compare the average number of copies per append for n = 10, 1 000 and 1 000 000.
Starter file (write your code where it says pass # your code here):
def simulate(n, start_capacity):
pass # your code here
# ---- tests ----
for n in [10, 1000, 1000000]:
cap, r, c = simulate(n, 1)
print(f"n={n:8}: capacity {cap:8}, resizes {r:2}, copies {c:8}, copies per append {c / n:.2f}")
Expected output when your code is correct:
n= 10: capacity 16, resizes 4, copies 15, copies per append 1.50 n= 1000: capacity 1024, resizes 10, copies 1023, copies per append 1.02 n= 1000000: capacity 1048576, resizes 20, copies 1048575, copies per append 1.05
Hint
Model solution
def simulate(n, start_capacity):
capacity, size, resizes, copies = start_capacity, 0, 0, 0
for _ in range(n):
if size == capacity:
copies += size
capacity *= 2
resizes += 1
size += 1
return capacity, resizes, copies
# ---- tests ----
for n in [10, 1000, 1000000]:
cap, r, c = simulate(n, 1)
print(f"n={n:8}: capacity {cap:8}, resizes {r:2}, copies {c:8}, copies per append {c / n:.2f}")
Task 3: Inserting into a fixed-size array
In a static (fixed-size) array, inserting in the middle means shifting every later element one place to the right. Use a list created as [None] * capacity and a separate count. Write insert_at(arr, count, pos, item) that shifts elements from the end backwards, puts the item at pos, and returns (new_count, shifts). If the array is full or pos is outside 0 to count, return (count, -1). Then answer: what is the worst case number of shifts for n items, and why does inserting at the end cost nothing?
Starter file (write your code where it says pass # your code here):
def insert_at(arr, count, pos, item):
pass # your code here
# ---- tests ----
shelf = [None] * 6
n = 0
for pos, book in [(0, "Kim"), (0, "Dune"), (1, "Emma"), (3, "Zoo"), (0, "Atlas")]:
n, shifts = insert_at(shelf, n, pos, book)
print(f"insert {book!r} at {pos}: shifts {shifts} -> {shelf}")
print(insert_at(shelf, n, 9, "X"))
n, s = insert_at(shelf, n, 2, "Holes")
print(insert_at(shelf, n, 0, "Full?"))
Expected output when your code is correct:
insert 'Kim' at 0: shifts 0 -> ['Kim', None, None, None, None, None] insert 'Dune' at 0: shifts 1 -> ['Dune', 'Kim', None, None, None, None] insert 'Emma' at 1: shifts 1 -> ['Dune', 'Emma', 'Kim', None, None, None] insert 'Zoo' at 3: shifts 0 -> ['Dune', 'Emma', 'Kim', 'Zoo', None, None] insert 'Atlas' at 0: shifts 4 -> ['Atlas', 'Dune', 'Emma', 'Kim', 'Zoo', None] (5, -1) (6, -1)
Hint
Model solution
Inserting at position 0 shifts all n items, so the worst case is n shifts: O(n). Inserting at the end (pos = count) shifts nothing: O(1), as long as there is space.
def insert_at(arr, count, pos, item):
if count == len(arr) or not 0 <= pos <= count:
return count, -1
shifts = 0
for i in range(count, pos, -1):
arr[i] = arr[i - 1]
shifts += 1
arr[pos] = item
return count + 1, shifts
# ---- tests ----
shelf = [None] * 6
n = 0
for pos, book in [(0, "Kim"), (0, "Dune"), (1, "Emma"), (3, "Zoo"), (0, "Atlas")]:
n, shifts = insert_at(shelf, n, pos, book)
print(f"insert {book!r} at {pos}: shifts {shifts} -> {shelf}")
print(insert_at(shelf, n, 9, "X"))
n, s = insert_at(shelf, n, 2, "Holes")
print(insert_at(shelf, n, 0, "Full?"))
Learning objectives
By the end of this page you should be able to:
- Define static and dynamic data structures.
- Explain how each allocates memory and resizes: fixed contiguous blocks, dynamic arrays that copy to a bigger block, and linked lists of nodes with pointers.
- Compare static and dynamic structures in terms of speed, memory usage and flexibility.
- Justify the choice of a static or dynamic structure for a given scenario.
Definitions
- A static data structure has a fixed size, set when it is created. Its memory is allocated once, usually as one contiguous block, and cannot grow or shrink while the program runs. Example: a Java array
int[] hours = new int[7]; - A dynamic data structure can grow and shrink at run time. Memory is allocated (and freed) as needed, from the heap. Examples: Python
list, JavaArrayList, linked lists.
How dynamic structures resize
- Dynamic array (Python list, Java ArrayList): keeps spare capacity. When it is full, it allocates a bigger block (often about 1.5 to 2 times larger), copies every element across and frees the old block. Most appends are fast; the occasional resize is slow, so the amortised cost per append is still constant.
- Linked list: each item is a node holding data and a pointer (reference) to the next node. Nodes are allocated one at a time anywhere in memory, so it never needs to copy, but every node pays extra memory for its pointer.
Comparison
| Factor | Static (e.g. array) | Dynamic (e.g. list, linked list) |
|---|---|---|
| Size | Fixed at creation | Changes at run time |
| Memory allocation | All at once, before use, contiguous | As needed, from the heap; may be scattered (linked list) |
| Memory usage | Can waste memory if not full; can overflow if too small | Matches the data more closely, but has overhead: spare capacity or pointers |
| Speed: access by index | Very fast, O(1): address = start + index × size | Dynamic array: also O(1). Linked list: must follow pointers, O(n) |
| Speed: insert/delete | Middle or front: shift elements. Impossible beyond the size | Linked list: just change pointers. Dynamic array: shifting, plus occasional resize copying |
| Flexibility | Low: the maximum must be known in advance | High: suits data whose size is unknown or changes |
| Complexity | Simple and predictable; good for embedded or real-time systems | More complex; risk of fragmentation and memory leaks if not managed |
Choosing
Use a static structure when the number of items is known and fixed (7 days, 12 months, a 3x3 board). Use a dynamic structure when the amount of data is unknown or changes (a catalogue, a waitlist, loan history).
Python note: Python has no true static array in everyday code. A tuple is fixed-size (and immutable), the array module stores typed values compactly, and a list made with [0] * 7 that you never resize behaves like a static array.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Outline what is meant by a dynamic data structure. [2]
2. Compare static and dynamic data structures in terms of memory usage. [4]
3. Appending to a Python list is usually very fast, but occasionally one append takes much longer. Explain why. [3]
4. ShelfWise stores the library's opening hours for each day of the week. Justify the use of a static data structure. [2]
5. Explain one disadvantage of a linked list compared with an array when retrieving the 500th item. [2]
6. The reservation waitlist for a popular book may hold 0 to several hundred students, and students join and leave all the time. Compare a static array and a dynamic structure for storing it, and recommend one. [4]