B2.2.2 Programming with arrays and lists
SL + HLCommand term: Construct1. 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.
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.
catalogue4. Python lists and Java arrays and ArrayLists
The syllabus names Java ArrayLists and arrays. Click a row to compare.
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.
7. 45-second speed round: index it
A new list each time. Evaluate the expression.
[title, author, copies]. Write the functions that add, find (by traversal), remove and total the books.Expected output
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
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: 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):
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
Model solution
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]))
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):
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
Model solution
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"]]))
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):
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
Model solution
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:
- Construct programs that use 1D and 2D Lists in Python, and 1D and 2D arrays and ArrayLists in Java.
- Add, insert and remove elements in a dynamic list, and explain the effect of shifting.
- Traverse 1D lists with a loop and 2D lists with nested loops.
- 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.
| Task | Python list | Java ArrayList |
|---|---|---|
| Create | books = [] | ArrayList<String> books = new ArrayList<>(); |
| Add at end | books.append("Dune") | books.add("Dune"); |
| Insert at index | books.insert(0, "Emma") | books.add(0, "Emma"); |
| Read / change | books[1] / books[1] = "Kim" | books.get(1) / books.set(1, "Kim"); |
| Remove by index | books.pop(1) or del books[1] | books.remove(1); |
| Remove by value | books.remove("Kim") (first match) | books.remove("Kim"); |
| Length | len(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 = adoes not copy a list: both names refer to the same list. Usea.copy().[[0] * 3] * 2makes 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])
['Dune', 'Holes', 'Emma'] 3 Emma [1].2. Distinguish between a Java array and a Java ArrayList. [2]
3. scores is a 2D list: each row holds one student's test scores. Construct code that prints each student's average. [4]
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]
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]
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].