Home › Theme B › B2 › B2.2 › B2.2.1

B2.2.1 Static vs dynamic data structures

SL + HLCommand term: Compare

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

Structure:
other dataallocated, emptyarray itemnode datanode pointerfree
Access item 0

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.

Books to add: 20   Static array size: 10   Dynamic start capacity: 1

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: true or false?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 2, task 1. Sprint 2 turns ShelfWise from single variables into collections. Before coding, make a design decision for each collection: static or dynamic, and why. Then write code that uses one of each, and watch Python resize a list behind the scenes.

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

    Next task (B2.2.2): the catalogue becomes a 2D list of books (title, author, copies), and you add, remove and traverse it.

    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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

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

    File: b2_2_1_average.py
    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
    The list never changes length; only count changes.
    Model solution
    File: b2_2_1_average_solution.py
    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)
    
    Moderate

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

    File: b2_2_1_moderate.py
    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
    Every resize copies all the current elements. Count them.
    Model solution
    File: b2_2_1_moderate_solution.py
    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}")
    
    Challenging

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

    File: b2_2_1_challenging.py
    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
    Loop i from count down to pos + 1, copying arr[i - 1] into arr[i].
    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.

    File: b2_2_1_challenging_solution.py
    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:

    1. Define static and dynamic data structures.
    2. 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.
    3. Compare static and dynamic structures in terms of speed, memory usage and flexibility.
    4. 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, Java ArrayList, 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

    FactorStatic (e.g. array)Dynamic (e.g. list, linked list)
    SizeFixed at creationChanges at run time
    Memory allocationAll at once, before use, contiguousAs needed, from the heap; may be scattered (linked list)
    Memory usageCan waste memory if not full; can overflow if too smallMatches the data more closely, but has overhead: spare capacity or pointers
    Speed: access by indexVery fast, O(1): address = start + index × sizeDynamic array: also O(1). Linked list: must follow pointers, O(n)
    Speed: insert/deleteMiddle or front: shift elements. Impossible beyond the sizeLinked list: just change pointers. Dynamic array: shifting, plus occasional resize copying
    FlexibilityLow: the maximum must be known in advanceHigh: suits data whose size is unknown or changes
    ComplexitySimple and predictable; good for embedded or real-time systemsMore 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]

    A data structure whose size can change (grow or shrink) during execution [1]; memory is allocated and released as needed at run time / from the heap [1].

    2. Compare static and dynamic data structures in terms of memory usage. [4]

    Both store collections of data in memory [1]. Static: memory is allocated once at a fixed size, so space is wasted if it is not full / it can overflow if it is too small [1]. Dynamic: memory is allocated as needed, so it uses roughly the memory the data requires [1], but it has overhead such as pointers in each node or spare capacity in a dynamic array [1].

    3. Appending to a Python list is usually very fast, but occasionally one append takes much longer. Explain why. [3]

    A Python list is a dynamic array with spare capacity, so most appends just write into a free slot [1]. When the capacity is used up, a larger block of memory must be allocated [1] and every existing element copied into it, which takes time proportional to the number of elements [1].

    4. ShelfWise stores the library's opening hours for each day of the week. Justify the use of a static data structure. [2]

    There are always exactly 7 days, so the size is known and fixed / will never need resizing [1]; a static array gives fast direct access by day index and uses no extra memory for pointers or spare capacity [1].

    5. Explain one disadvantage of a linked list compared with an array when retrieving the 500th item. [2]

    A linked list has no direct index access: it must be traversed from the head, following 499 pointers [1], so retrieval is O(n) / slower than an array, which calculates the address directly in O(1) [1].

    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]

    Static array: must be sized for the maximum, wasting memory most of the time, and overflows if the estimate is too low [1]; removing a student from the middle means shifting elements [1]. Dynamic (e.g. list / linked list): grows and shrinks with the waitlist so memory matches demand [1]. Recommendation: dynamic, because the size is unknown and changes frequently; the small pointer/capacity overhead is acceptable [1].