Python Chapter 6 — arrays, lists and dictionaries

← Index · Solutions

Priority key · Priorities guide emphasis; they do not remove taught scope.

Exam recall

Assignment aliases; a shallow copy may share inner rows. Derive row/column bounds and reset accumulators at the correct loop level. Dictionary membership tests keys.

Arrays, lists and dictionaries priority/medium

Choose a collection by what makes an item findable: a list preserves a sequence of positions; a dictionary associates a key with a value. If the task asks for “the count for each word”, the word is naturally a dictionary key. If it asks for “every matching occurrence in the original order”, a result list naturally preserves those occurrences.

In the school model, an array is an indexed collection, commonly with a fixed size and uniform element type. A Python list is a mutable, dynamically sized sequence that can hold references to different types. It can be used to implement a school-style fixed-capacity array by preallocating storage and maintaining separate logical state.

List operationMeaning
values.append(x)Add one item at the end; returns None.
values.extend(items)Add each item from another iterable.
values.insert(i, x)Insert at a position, shifting later items.
values.pop(i)Remove and return the item at i; default last.
values.remove(x)Remove the first equal value; fails if absent.
values[i] = xReplace an existing element.

Do not write values = values.append(x); it replaces the list reference with None. Membership x in values asks whether a value occurs, not where. Traversal by index is useful when modifying positions; traversal by value is often clearer for counting/summing.

Aliasing and two-dimensional lists priority/high

flowchart LR
    A[Name a] --> L[One list object]
    B[Name b after b = a] --> L
    C[Name c after c = a copy] --> M[Different outer list]

The diagram concerns an outer list. A shallow copy of a nested list still points to the same inner rows. Copying a reference does not copy the object; copying the outer list does not necessarily copy its inner lists.

b = a refers to the same list; changing b[0] affects a. b = a[:] copies the outer list, but nested lists can still be shared. For an independent rectangular grid, create a fresh row each time:

def make_grid(rows, columns):
    return [[0 for column in range(columns)] for row in range(rows)]  # Fresh row each time.

Avoid [[0] * columns] * rows: the row references are repeated, so one cell update can appear in every row. Access grid[row][column]. Check the problem’s coordinate convention before treating x as a row or y as a column.

For a rectangular grid with r rows and c columns, valid row indices are 0..r−1 and column indices 0..c−1. Main-diagonal square cells satisfy row=column; opposite-diagonal cells satisfy row+column=n−1. If a simulation updates every cell simultaneously, compute a new grid from the old one, then replace it; otherwise later cells may read already-updated neighbours.

For neighbour problems, derive candidate coordinates first and keep only those satisfying both row and column bounds. At a corner there are fewer valid neighbours than in the interior. If the update is simultaneous, every neighbour value must come from the same old grid, not a partly updated one.

Dictionaries priority/high

A dictionary maps unique, hashable keys to values. d[key] retrieves a value and raises KeyError if missing; d.get(key, default) supplies a fallback. Assigning an existing key replaces its value. key in d tests keys. Iterating d.items() gives key–value pairs. Dictionary keys are not list positions unless that is deliberately the chosen key scheme.

Use del d[key] to remove an existing entry, or d.pop(key, default) to remove and return a value with an optional missing-key fallback. Choosing a list versus dictionary changes the meaning of membership: list membership searches values; dictionary membership checks keys.

def frequencies(items):
    counts = {}
    for item in items:
        counts[item] = counts.get(item, 0) + 1  # First occurrence starts from zero.
    return counts

For ["cat", "dog", "cat"], cat progresses 0→1→2 and dog 0→1. This counts occurrences rather than storing duplicates as repeated keys.

Worked example — adapted from HCI 2024 Q9 grid skills priority/high

Return all row indices with the greatest total. Empty grid returns []; rows contain numbers.

def fullest_rows(grid):
    best = None
    result = []
    for row_index in range(len(grid)):
        total = sum(grid[row_index])
        if best is None or total > best:  # First row or a new strict maximum.
            best = total
            result = [row_index]  # Previous candidates are no longer maximal.
        elif total == best:  # Equal maxima are additional answers.
            result.append(row_index)
    return result

For [[1,0,1], [0,1,0], [1,1,0]], totals are 2,1,2 and result [0,2]. A new strict maximum discards previous candidates; an equal maximum adds a tie. If the exam disallows sum, replace it with an explicit accumulator loop.

Practice

Exam focus: HCI 2024 Q9 asks for 2D occupancy calculations and tied maximum rows; HCI 2023 Q8 uses bounded grid movement; HCI 2022 modified Q9 includes simultaneous grid updates. Use the original 2024 Q9, PDF p.6 to practise distinguishing a count, a list of row indices and a Boolean condition.

Approach: decide output shape → choose traversal direction → place each accumulator at the correct loop level → handle ties/duplicates → test a nonsquare grid. A 2×3 grid exposes swapped row/column bounds that a square grid can hide.

17A — original. Write column_totals(grid) for a nonempty rectangular numeric grid, returning one total per column. For [[1,2,3],[4,5,6]], give the result. Explain where the total must reset.

17B — original. Write most_frequent(items) returning every distinct item tied for greatest frequency, in order of first appearance. Items are strings; empty input returns []. Test ["b","a","b","a","c"].

Revision checklist

  • 17.1 Distinguish a fixed-size array model from Python’s dynamic list.
  • 17.2 Create, traverse, insert, look up, update and delete list items.
  • 17.3 Predict the effects and return values of the taught list methods.
  • 17.4 Distinguish aliasing, shallow copying and independent nested lists.
  • 17.5 Create and traverse 2D lists using consistent row/column conventions.
  • 17.6 Solve row, column, diagonal, neighbour and accumulation tasks within index bounds.
  • 17.7 Use dictionaries for lookup, insertion, update, deletion and frequency counting.
  • 17.8 Handle missing dictionary keys and duplicate inputs according to the task.
  • 17.9 Choose a suitable collection and justify the choice.
  • 17.10 Generate random data with the correct inclusive/exclusive bounds.

Visual revision mindmap

Chapter 17 revision mindmap

Open this mindmap and its text version · All 21 mindmaps

Your mindmap framework

Centre: Python Chapter 6 — arrays, lists and dictionaries. Build the six branches below. For each subbranch, add a short definition, a labelled sample and one exam trap from memory; then check the chapter.

flowchart LR
    C["17 • Revision map"]
    C --> B0["Choose a collection"]
    C --> B1["List operations"]
    C --> B2["References and copies"]
    C --> B3["Two-dimensional data"]
    C --> B4["Dictionaries"]
    C --> B5["Visual checks and mistakes"]
  • Choose a collection

    • School array: indexed, typically fixed and homogeneous.
    • Python list: dynamic mutable sequence.
    • Dictionary: key → value mapping.
    • Match structure to access and output requirements.
  • List operations

    • append versus extend.
    • insert, replace, remove and pop.
    • Membership searches values.
    • Mutation methods may return None; preserve required order.
  • References and copies

    • Assignment: same object.
    • Shallow copy: new outer container.
    • Nested objects may still be shared.
    • Fresh row per grid row prevents aliasing.
  • Two-dimensional data

    • Row/column convention and bounds.
    • Rows, columns and two diagonals.
    • Neighbours: candidate coordinates then bounds.
    • Simultaneous updates use old grid and a separate new grid.
  • Dictionaries

    • Unique hashable keys.
    • Insert/update/delete and lookup.
    • Missing key: KeyError versus get fallback.
    • Frequency count, maximum count and distinct tied outputs.
  • Visual checks and mistakes

    • Draw two names pointing to one list.
    • Draw non-square grid with row/column indices.
    • Trace accumulator reset and tie handling.
    • Avoid: list = list.append(…); repeated row reference; dictionary membership tests values.

Close the notes and test the map: explain one branch aloud, sketch its sample, then answer a linked practice question. Mark any missing link to revisit.

Source trail

9569 §1.2.5; school Array, List and Dictionary.

HCI 2022 Q9; 2023 Q8; 2024 Q9; 2025 Q8.

Source guide records provenance and original-paper locations.