Home › Theme B › B2 › B2.2 › B2.2.2

B2.2.2 Programming with arrays and lists

SL + HLCommand term: Construct

1. A list in action

Step through a ShelfWise list of copies on the shelf: create it, read by index, traverse it with a loop, then add and remove elements. Yellow boxes moved; green boxes are new.

2. List operations workbench

Run real list operations on books. Watch which elements shift and read Python's exact errors when you get an index or value wrong.

Operation:
Result: -
books =
Choose an operation and press Run.

3. 2D list explorer: the catalogue table

A 2D list is a list of lists: catalogue[row][column]. Click any cell, type an expression, or animate a nested-loop traversal.

catalogue
Value: -
Rows are books; columns are 0 title, 1 author, 2 copies.

4. Python lists and Java arrays and ArrayLists

The syllabus names Java ArrayLists and arrays. Click a row to compare.

Click a row.

5. Flip-card deck

Click to flip. Say the answer before you flip.

6. Predict the output

Trace each snippet. Streaks of 3+ score double.

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

7. 45-second speed round: index it

A new list each time. Evaluate the expression.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 2, task 2. The catalogue becomes a 2D list: one row per book, columns [title, author, copies]. Write the functions that add, find (by traversal), remove and total the books.

Expected output

2 -1 True False Total copies: 7 Dune by Frank Herbert (2) Holes by Louis Sachar (4) Matilda by Roald Dahl (1) Holes 3

Think about it

(1) Why do the named constants TITLE, AUTHOR, COPIES make the code easier to read? (2) Why does find_book compare in lower case? (3) What would happen if remove_book deleted rows while a for loop was traversing the same list?

Check my code

    Next task (B2.2.3): every catalogue change is pushed onto a stack so the librarian can press Undo.

    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: Class results without built-ins

    Write stats(marks) that returns the highest mark, the lowest mark and the mean (rounded to 1 decimal place), without using max, min, sum or sorted.

    Starter file (write your code where it says pass # your code here):

    File: b2_2_2_average.py
    def stats(marks):
        pass  # your code here
    
    # ---- tests ----
    print(stats([67, 82, 45, 90, 73]))
    print(stats([50]))
    

    Expected output when your code is correct:

    (90, 45, 71.4)
    (50, 50, 50.0)
    Hint
    Traverse the list once, updating three variables.
    Model solution
    File: b2_2_2_average_solution.py
    def stats(marks):
        high = low = marks[0]
        total = 0
        for m in marks:
            if m > high:
                high = m
            if m < low:
                low = m
            total += m
        return high, low, round(total / len(marks), 1)
    
    # ---- tests ----
    print(stats([67, 82, 45, 90, 73]))
    print(stats([50]))
    
    Moderate

    Task 2: Exam hall seating plan (2D list)

    A seating plan is a 2D list where each seat holds a name or None. Write empty_per_row(plan) returning a list of empty-seat counts per row, and first_empty(plan) returning the (row, seat) position of the first empty seat, scanning row by row, or None if the hall is full.

    Starter file (write your code where it says pass # your code here):

    File: b2_2_2_moderate.py
    def empty_per_row(plan):
        pass  # your code here
    
    def first_empty(plan):
        pass  # your code here
    
    # ---- tests ----
    plan = [["Ana", "Ben", None, "Cai"],
            ["Dev", "Eli", "Fay", "Gus"],
            [None, "Hui", None, None]]
    print(empty_per_row(plan))
    print(first_empty(plan))
    print(first_empty([["X", "Y"], ["Z", "W"]]))
    

    Expected output when your code is correct:

    [1, 0, 3]
    (0, 2)
    None
    Hint
    Use a nested loop: the outer loop over rows, the inner loop over seats in a row.
    Model solution
    File: b2_2_2_moderate_solution.py
    def empty_per_row(plan):
        return [sum(1 for seat in row if seat is None) for row in plan]
    
    def first_empty(plan):
        for r, row in enumerate(plan):
            for s, seat in enumerate(row):
                if seat is None:
                    return (r, s)
        return None
    
    # ---- tests ----
    plan = [["Ana", "Ben", None, "Cai"],
            ["Dev", "Eli", "Fay", "Gus"],
            [None, "Hui", None, None]]
    print(empty_per_row(plan))
    print(first_empty(plan))
    print(first_empty([["X", "Y"], ["Z", "W"]]))
    
    Challenging

    Task 3: Noughts and crosses winner

    A 3 × 3 board is a 2D list of "X", "O" or " ". Write winner(board) that returns "X" or "O" if a player has three in a row (row, column or diagonal), "draw" if the board is full with no winner, and "playing" otherwise. Try to check all eight lines with loops rather than eight separate if statements.

    Starter file (write your code where it says pass # your code here):

    File: b2_2_2_challenging.py
    def winner(board):
        pass  # your code here
    
    # ---- tests ----
    print(winner([["X", "O", "X"], [" ", "X", "O"], ["O", " ", "X"]]))
    print(winner([["O", "X", " "], ["O", "X", " "], ["O", " ", "X"]]))
    print(winner([["X", "O", "X"], ["X", "O", "O"], ["O", "X", "X"]]))
    print(winner([["X", " ", " "], [" ", "O", " "], [" ", " ", " "]]))
    

    Expected output when your code is correct:

    X
    O
    draw
    playing
    Hint
    Build a list of all eight lines, then check each line the same way.
    Model solution
    File: b2_2_2_challenging_solution.py
    def winner(board):
        lines = []
        for i in range(3):
            lines.append(board[i])                              # rows
            lines.append([board[r][i] for r in range(3)])       # columns
        lines.append([board[i][i] for i in range(3)])           # diagonal
        lines.append([board[i][2 - i] for i in range(3)])       # other diagonal
        for line in lines:
            if line[0] != " " and line.count(line[0]) == 3:
                return line[0]
        if all(cell != " " for row in board for cell in row):
            return "draw"
        return "playing"
    
    # ---- tests ----
    print(winner([["X", "O", "X"], [" ", "X", "O"], ["O", " ", "X"]]))
    print(winner([["O", "X", " "], ["O", "X", " "], ["O", " ", "X"]]))
    print(winner([["X", "O", "X"], ["X", "O", "O"], ["O", "X", "X"]]))
    print(winner([["X", " ", " "], [" ", "O", " "], [" ", " ", " "]]))
    

    Learning objectives

    By the end of this page you should be able to:

    1. Construct programs that use 1D and 2D Lists in Python, and 1D and 2D arrays and ArrayLists in Java.
    2. Add, insert and remove elements in a dynamic list, and explain the effect of shifting.
    3. Traverse 1D lists with a loop and 2D lists with nested loops.
    4. Avoid common errors: off-by-one indexes, removing while traversing, and aliasing.

    Arrays

    An array is a fixed-size, ordered collection of elements of the same type, stored contiguously and accessed by an index starting at 0. In Java: int[] copies = new int[5]; creates 5 integers (all 0). copies.length is 5; copies[5] throws ArrayIndexOutOfBoundsException.

    Lists and ArrayLists

    A Python list and a Java ArrayList are dynamic: they grow and shrink (B2.2.1). A Python list can even mix types, although ShelfWise keeps each column consistent.

    TaskPython listJava ArrayList
    Createbooks = []ArrayList<String> books = new ArrayList<>();
    Add at endbooks.append("Dune")books.add("Dune");
    Insert at indexbooks.insert(0, "Emma")books.add(0, "Emma");
    Read / changebooks[1] / books[1] = "Kim"books.get(1) / books.set(1, "Kim");
    Remove by indexbooks.pop(1) or del books[1]books.remove(1);
    Remove by valuebooks.remove("Kim") (first match)books.remove("Kim");
    Lengthlen(books)books.size()
    Search"Dune" in books, books.index("Dune")books.contains("Dune"), books.indexOf("Dune")

    Inserting or removing near the front shifts every later element, so it is slower than working at the end.

    Traversal

    for title in books:              # by value: simplest
        print(title)
    
    for i in range(len(books)):      # by index: when you need the position
        print(i, books[i])

    2D lists and arrays

    A 2D structure is a grid of rows and columns: a list of lists. catalogue[r][c] picks row r, then column c. Traverse with a nested loop, usually row by row (row-major order).

    desks = [[False] * 6 for _ in range(5)]   # 5 rows x 6 columns, all free
    desks[2][3] = True                         # row 2, column 3 taken
    
    for r in range(len(desks)):                # rows
        for c in range(len(desks[r])):         # columns in this row
            print(desks[r][c], end=" ")
        print()

    Java: boolean[][] desks = new boolean[5][6]; and desks.length (rows), desks[0].length (columns).

    Pitfalls

    • Off-by-one: the last index is len(list) - 1.
    • remove(x) removes the first element equal to x, not the element at index x.
    • Do not add to or remove from a list while a for loop is traversing it: traverse a copy, or build a new list.
    • b = a does not copy a list: both names refer to the same list. Use a.copy().
    • [[0] * 3] * 2 makes two references to one row. Use [[0] * 3 for _ in range(2)].

    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. State the output of the code. [3]

    books = ["Dune", "Emma", "Kim"]
    books.insert(1, "Holes")
    books.remove("Kim")
    print(books, len(books), books[-1])
    After insert: ['Dune', 'Holes', 'Emma', 'Kim'] [1]; after remove: ['Dune', 'Holes', 'Emma'] [1]; output ['Dune', 'Holes', 'Emma'] 3 Emma [1].

    2. Distinguish between a Java array and a Java ArrayList. [2]

    An array has a fixed size set when it is created / is static, accessed with [ ] and .length [1]; an ArrayList can grow and shrink at run time / is dynamic, using methods such as add(), remove(), get() and size() [1].

    3. scores is a 2D list: each row holds one student's test scores. Construct code that prints each student's average. [4]

    Outer loop over the rows, e.g. for row in scores: [1]; inner loop / sum over the columns of that row, total reset for each student [1]; divide by the number of scores in the row, len(row) [1]; print one average per student [1].
    for row in scores:
        total = 0
        for s in row:
            total = total + s
        print(total / len(row))

    4. Construct a function remove_unavailable(catalogue) that returns a new list containing only rows where the copies (column 2) are greater than 0. [4]

    Create an empty result list [1]; traverse every row [1]; test row[2] > 0 [1]; append qualifying rows and return the result [1]. (Removing from the list while traversing it is not credited, because elements are skipped.)

    5. A 2D array desks has 5 rows and 6 columns. State (a) the expression for the last desk in the third row, (b) the number of elements. [2]

    (a) desks[2][5] [1]; (b) 5 × 6 = 30 [1].

    6. Construct Java code that creates an ArrayList of Strings, adds "Dune" and "Emma", inserts "Kim" at the front and prints its size. [3]

    ArrayList<String> books = new ArrayList<>(); [1]; books.add("Dune"); books.add("Emma"); books.add(0, "Kim"); [1]; System.out.println(books.size()); printing 3 [1].