IB COMPUTER SCIENCE | B2.2.2 Arrays and Lists

Lesson objective

Construct programs using 1D and 2D arrays and lists, applying indexing, updates, dynamic add/remove operations and traversal in Python and Java.

Learn

B2.2.2 | ARRAYS AND LISTS

01 | ONE NAME, MANY RELATED VALUES

A program could store score1, score2 and score3, but that becomes awkward when a fourth score arrives or you need to process every score. A collection keeps related entries together under one name and provides a way to access them.

An array stores indexed elements, with a fixed length in the Java examples here. A Python list is a dynamic indexed collection. Java ArrayList is also dynamic. We will construct programs using each, then organise data into two dimensions.

This common SL/HL lesson covers 1D and 2D Java arrays, Java ArrayLists and 1D and 2D Python lists, including adding, removing and traversing entries. Start with the Python path; the Java examples show the corresponding language structures.

02 | CREATE A ONE-DIMENSIONAL LIST

scores = [12, 18, 15]
names = ["Maya", "Leo", "Aisha"]
empty_scores = []
print(scores)
print(len(scores))  # 3
index 0 12
index 1 18
index 2 15

One-dimensional means one index selects an element. The list literal uses square brackets and commas. len gives the number of entries, not the final index.

Python permits mixed types, but a numeric-score collection is clearer when every entry has the intended numeric meaning. A list of three names has length three even though the names themselves contain several characters.

03 | READ AND REPLACE BY INDEX

scores = [12, 18, 15]
print(scores[0])  # 12
print(scores[2])  # 15
scores[1] = 20
print(scores)     # [12, 20, 15]

Indexes begin at 0. Reading scores[1] gets the second element; assigning scores[1] replaces that element. Replacement keeps the list length unchanged.

For a nonempty list, index −1 accesses the last entry in Python. Index len(scores) is outside the existing entries. An empty list has no first or last entry to read.

A single-item access outside the available range raises IndexError. A list name is not one of its values: scores is the collection, while scores[0] is one element.

04 | APPEND AND INSERT ARE DIFFERENT

scores = [12, 18, 15]
scores.append(9)
print(scores)  # [12, 18, 15, 9]
scores.insert(1, 14)
print(scores)  # [12, 14, 18, 15, 9]

append adds one entry at the end. insert(index, value) adds before the selected position, shifting subsequent entries to later indexes. Both increase length by one.

If you replace scores[1], you overwrite an existing entry. If you insert at index 1, the previous second entry remains but moves to index 2. Predict which you need from the requirement.

Python insert clips very large or negative insertion positions according to its rules. For beginner construction tasks, explicitly use an insertion position from 0 through len(scores); the explorer enforces that range.

05 | REMOVE BY VALUE OR REMOVE BY POSITION

scores = [12, 18, 12, 15]
scores.remove(12)
print(scores)      # [18, 12, 15]
removed = scores.pop(1)
print(removed)     # 12
print(scores)      # [18, 15]
last = scores.pop()
print(last)        # 15

remove(value) deletes the first equal value. It does not treat its argument as an index. pop(index) removes the entry at that position and returns it; pop() uses the last position.

Removing a missing value raises ValueError. Popping from an empty list or an invalid index raises IndexError. Check the requirement and current collection before the operation.

After a removal, following entries shift left and indexes change. An index identifies the current position, not a permanent record identity.

06 | MUTATING METHODS AND RETURNED VALUES

scores = [12, 18]
result = scores.append(15)
print(scores)  # [12, 18, 15]
print(result)  # None

append changes the existing list and returns None. Do not write scores = scores.append(15), which rebinds scores to None and loses that name’s access to the list. insert and remove also mutate without returning the updated list.

pop is different: it mutates the list and returns the removed entry. Use that return value when the program needs to display or process what was removed.

A Python list is mutable, unlike a string. Element replacement and append change the same list object; this matters when another name refers to it.

07 | TRAVERSE THE VALUES

scores = [12, 18, 15]
for score in scores:
    print(score)

Traversal means visiting each entry. Here score receives 12, then 18, then 15. The indented loop body runs once per entry.

Use a value loop when you need each value but not its position. An empty list causes zero body executions, not an error merely because it is empty.

Changing score alone inside this loop does not replace the corresponding list element. To update stored entries, use indexed assignment.

08 | TRAVERSE USING INDEXES

scores = [12, 18, 15]
for index in range(len(scores)):
    scores[index] = scores[index] + 1
print(scores)  # [13, 19, 16]

range(len(scores)) supplies indexes 0, 1 and 2. The stop is excluded, so index 3 is never generated. Each assignment reads and replaces the selected entry.

Use an index loop when position matters or values must be updated in the collection. Keep the collection length stable during this simple traversal.

Adding or removing entries while traversing the same list can skip entries or create other unintended behaviour. A separate result list is often clearer when filtering.

09 | TOTAL, COUNT AND AVERAGE

scores = [12, 18, 15]
total = 0
count_high = 0
for score in scores:
    total = total + score
    if score >= 15:
        count_high = count_high + 1
print("Total:", total)       # 45
print("At least 15:", count_high)  # 2
if len(scores) > 0:
    print("Average:", total / len(scores))  # 15.0
else:
    print("No scores for an average")

Initialise the accumulators before the loop. total preserves the old sum and adds the current score; count_high increases only for qualifying entries.

The average needs a nonzero number of entries. An empty list has a valid sum of zero under this algorithm, but no ordinary arithmetic mean to calculate.

10 | BUILD A NEW LIST WHILE FILTERING

scores = [12, 18, 15, 9]
selected = []
for score in scores:
    if score >= 15:
        selected.append(score)
print(selected)  # [18, 15]
print(scores)    # [12, 18, 15, 9]

The new list records qualifying entries in traversal order. The source list remains unchanged because we do not remove from it during its own traversal.

This explicit version makes the condition, append and accumulated result visible. Python comprehensions can express similar work more compactly, but the algorithm is the same selection-and-collection idea.

11 | INTERACTIVE: EDIT AND TRAVERSE A LIST

Start with [10, 20, 30]. Choose an operation, predict the resulting list, then apply it. Value fields accept whole numbers from −99 to 99. Index fields use non-negative positions; insertion permits the position immediately after the last entry. The activity limits length to eight entries.

Any edit restarts traversal, so a running total never mixes two versions of the list. Removing a missing value is reported without changing the collection. This activity shows logical entries, not internal spare capacity.

12 | JAVA: CREATE AND TRAVERSE A 1D ARRAY

public class ArrayExample {
    public static void main(String[] args) {
        int[] scores = {12, 18, 15};
        scores[1] = 20;
        int total = 0;
        for (int index = 0; index < scores.length; index++) {
            total = total + scores[index];
        }
        System.out.println(total); // 47
    }
}

Java array access also starts at 0. scores.length gives the fixed array length. The condition index < scores.length avoids trying to read the out-of-range index equal to the length.

Java declares the element type using int[]. This array cannot grow using append. Updating scores[1] replaces an entry without changing the length.

13 | JAVA: A DYNAMIC ARRAYLIST

import java.util.ArrayList;

public class ListExample {
    public static void main(String[] args) {
        ArrayList<Integer> scores = new ArrayList<>();
        scores.add(12);
        scores.add(18);
        scores.add(15);
        scores.add(1, 14);
        scores.set(0, 10);
        int removed = scores.remove(2);
        int total = 0;
        for (int score : scores) {
            total = total + score;
        }
        System.out.println(scores);  // [10, 14, 15]
        System.out.println(removed); // 18
        System.out.println(total);   // 39
    }
}

add(value) appends; add(index, value) inserts; get(index) reads; set(index, value) replaces; size() reports the current number of entries. Integer is the reference type used for the generic collection.

Do not mix Java array syntax with ArrayList method syntax. The collection operations correspond conceptually to Python operations, but their exact names and return values differ.

14 | JAVA INTEGER REMOVAL: WATCH THE OVERLOAD

import java.util.ArrayList;

public class RemovalExample {
    public static void main(String[] args) {
        ArrayList<Integer> scores = new ArrayList<>();
        scores.add(10);
        scores.add(20);
        scores.add(10);
        scores.remove(1);                  // remove index 1: value 20
        scores.remove(Integer.valueOf(10)); // remove first equal value 10
        System.out.println(scores);       // [10]
    }
}

ArrayList has overloaded remove operations. With an int argument, remove(1) removes the entry at index 1. To remove a boxed integer value, Integer.valueOf makes that intention explicit.

Python list.remove(1), in contrast, removes the first value equal to 1, not position 1. Use Python pop(1) for positional removal. Knowing the concept is essential, but you must still apply the chosen language’s rules.

15 | ONE DIMENSION OR TWO?

A single index suits a sequence of scores. A seating layout or several students’ scores across tests needs two coordinates. A rectangular two-dimensional structure can be viewed as rows and columns.

For our grid, the first index selects a row and the second selects a column within that row. State this convention and keep it consistent. grid[1][2] means row 1, column 2, not the other way round.

Row / column Column 0 Column 1 Column 2
Row 0 4 7 2
Row 1 5 1 6

There are two rows, three columns in each row and six entries altogether. Python and Java can also represent unequal row lengths; rectangularity is a requirement of this example, not an automatic guarantee of every nested collection.

16 | PYTHON: CREATE A LIST OF ROW LISTS

grid = [
    [4, 7, 2],
    [5, 1, 6]
]
print(grid[0][1])  # 7
grid[1][2] = 9
print(grid[1])     # [5, 1, 9]
print(len(grid))   # 2 rows
print(len(grid[0]))  # 3 entries in row 0

The outer list stores references to row lists. Selecting grid[1] returns the second row; selecting [2] from that row reads its third element.

len(grid) counts rows, not all cells. len(grid[row]) counts entries in that particular row. An invalid row or column access can raise IndexError.

17 | BUILD INDEPENDENT ROWS

rows = 2
columns = 3
grid = []
for row in range(rows):
    new_row = [0] * columns
    grid.append(new_row)
grid[0][1] = 9
print(grid)  # [[0, 9, 0], [0, 0, 0]]

Each loop iteration constructs a new row list, so updating the first row does not unexpectedly update another row.

The tempting expression [[0] * columns] * rows repeats references to the same inner list. A change through one row reference then appears in every repeated row. This is aliasing, not a mysterious row/column indexing rule.

For immutable zero values, [0] * columns is suitable for each independent row. The problem arises when the same mutable inner row is repeated.

18 | NESTED LOOPS: VISIT EVERY CELL

grid = [[4, 7, 2], [5, 1, 6]]
total = 0
for row in range(len(grid)):
    for column in range(len(grid[row])):
        total = total + grid[row][column]
print(total)  # 25

The outer loop selects a row. For that row, the inner loop visits every column. The inner column sequence begins again for each new row.

The order is (0,0), (0,1), (0,2), (1,0), (1,1), (1,2). This row-by-row order is often called row-major traversal in this teaching context.

Using len(grid[row]) keeps the column bound tied to the current row. Assuming every row has the first row’s length is appropriate only when the rectangular format is guaranteed.

19 | TRACE THE NESTED TOTAL

row column Current value Old total + value New total
0 0 4 0 + 4 4
0 1 7 4 + 7 11
0 2 2 11 + 2 13
1 0 5 13 + 5 18
1 1 1 18 + 1 19
1 2 6 19 + 6 25

total is initialised once before both loops because this task needs a grand total. Moving total = 0 inside the outer loop would restart the sum for each row and leave only the final row’s total at the end.

A row-total task uses a separate initialisation inside the outer loop deliberately. The placement of the initialisation follows the meaning of the accumulator.

20 | INTERACTIVE: COORDINATES AND NESTED TRAVERSAL

Edit one cell in the two-row, three-column grid. Then step through a row-by-row total. The highlighted cell is the most recently processed cell. Editing restarts the trace so the total always belongs to the displayed data.

21 | ROW TOTALS AND COLUMN TOTALS

grid = [[4, 7, 2], [5, 1, 6]]

for row in range(len(grid)):
    row_total = 0
    for column in range(len(grid[row])):
        row_total = row_total + grid[row][column]
    print("Row", row, "total:", row_total)

# This part assumes a nonempty rectangular grid.
for column in range(len(grid[0])):
    column_total = 0
    for row in range(len(grid)):
        column_total = column_total + grid[row][column]
    print("Column", column, "total:", column_total)

The row totals are 13 and 12. The column totals are 9, 8 and 8. For column totals, the chosen column stays fixed while row changes.

The second loop pair assumes grid has a row and every row has the same length. Decide what an empty or ragged input means before applying an algorithm that requires a rectangle.

22 | JAVA: TWO-DIMENSIONAL ARRAYS

public class GridExample {
    public static void main(String[] args) {
        int[][] grid = {{4, 7, 2}, {5, 1, 6}};
        int total = 0;
        for (int row = 0; row < grid.length; row++) {
            for (int column = 0; column < grid[row].length; column++) {
                total = total + grid[row][column];
            }
        }
        System.out.println(grid[0][1]); // 7
        System.out.println(total);      // 25
    }
}

Java int[][] is an array whose elements refer to row arrays. The outer length counts rows; grid[row].length counts columns in that row. Rows can have different lengths unless the program requires a rectangular shape.

This is a logical 2D arrangement, not a promise that all row objects form one flat physical block. A dimension describes how you address the data, not a complete memory map.

23 | ADD AND REMOVE ROWS IN PYTHON

grid = [[4, 7, 2], [5, 1, 6]]
new_row = [8, 3, 4]
if len(new_row) == 3:
    grid.append(new_row)
removed_row = grid.pop(1)
print(grid)         # [[4, 7, 2], [8, 3, 4]]
print(removed_row)  # [5, 1, 6]

The outer list’s elements are rows, so append(new_row) adds one row and pop(1) removes a whole row. Updating grid[1][2] changes one cell instead.

Appending a value to only one row can make the structure ragged. If the problem requires three columns per row, validate row lengths when adding or changing data.

24 | REFERENCES AND COPYING

scores = [10, 20]
alias = scores
alias[0] = 99
print(scores)  # [99, 20]

copy_scores = scores.copy()
copy_scores[0] = 5
print(scores)  # [99, 20]

alias = scores gives another name for the same list, not an independent copy. A shallow copy creates a new outer list. For this flat list of integers, replacing an entry in the copy does not replace an entry in the original.

For nested lists, copying only the outer list still shares the row lists. If independent rows are needed, copy each row or choose a suitable deeper-copy strategy for the data. The shared-row construction mistake is another instance of the same reference issue.

25 | WORKED PROGRAM: A SCORE SUMMARY

def score_summary(scores):
    total = 0
    count_pass = 0
    for score in scores:
        total = total + score
        if score >= 50:
            count_pass = count_pass + 1
    if len(scores) == 0:
        return "No scores"
    average = total / len(scores)
    return "Average: " + str(average) + "; passes: " + str(count_pass)

print(score_summary([40, 60, 80]))
print(score_summary([]))

The first result is Average: 60.0; passes: 2. The empty case returns No scores instead of dividing by zero. Assume numeric scores in the required domain; a full input program should validate the values before storing them.

The function receives a list argument and reads it without altering its entries. Its local counters and total belong to the call.

26 | CONSTRUCT A PROGRAM: TEAM SCORES

Store two teams’ three round scores in a 2D Python list. Use [[4,7,2],[5,1,6]]. Print each team’s total, then the grand total. Use an inner loop for each team and make the accumulator placement explicit.

Reveal one possible solution
teams = [[4, 7, 2], [5, 1, 6]]
grand_total = 0
for team in range(len(teams)):
    team_total = 0
    for round_index in range(len(teams[team])):
        team_total = team_total + teams[team][round_index]
    print("Team", team, "total:", team_total)
    grand_total = grand_total + team_total
print("Grand total:", grand_total)

The totals are 13, 12 and 25. Team indexes are 0 and 1. team_total restarts for each team, while grand_total retains both contributions.

27 | CHOOSE THE RIGHT OPERATION

Requirement Python list Java ArrayList
Read position i items[i] items.get(i)
Replace position i items[i] = value items.set(i, value)
Append items.append(value) items.add(value)
Insert before position i items.insert(i, value) items.add(i, value)
Remove by position items.pop(i) items.remove(i) with int index
Remove an integer value items.remove(value) items.remove(Integer.valueOf(value))
Current number of entries len(items) items.size()

For Java arrays, use indexed access and .length, but add/remove operations do not resize that fixed array. A program can impose its own logical occupancy policy or explicitly create a different array.

28 | TEST THE COLLECTION, NOT ONLY ONE OUTPUT

For 1D programs, test empty, single-entry and multiple-entry collections; first and last positions; duplicates; and a missing removal value. Check length and order after an insertion or removal.

For 2D programs, test coordinate boundaries, different values in neighbouring cells, independent rows and the required rectangular or ragged shape. Distinct values make swapped row/column indexes easier to detect.

Verify that a traversal processes each intended entry once and that initialisation is at the right level. A grand total reset inside the row loop may look correct with only one row.

29 | COMMON MISTAKES

Mistake Correction
The first index is 1 Python and Java examples start at 0.
Insertion is replacement Insertion preserves and shifts later entries; replacement overwrites one.
remove always means index Python remove means value; Java overloads require care.
append returns the updated list Python append mutates and returns None.
len(grid) counts cells It counts outer entries, usually rows.
The second coordinate is always row This lesson uses row first, column second.
Repeated inner row references are independent Construct a new row object for each row.
A shallow outer copy makes every row independent Nested row references can remain shared.

30 | APPLY THE SKILL IN YOUR OWN PROGRAM

Can you create, read and update 1D and 2D structures, choose value or index traversal, and implement add/remove operations in the correct language? Can you trace indexes and totals and handle empty or invalid cases deliberately?

Use the construction questions to produce complete programs, then compare their results with worked answers. The next lesson uses collection operations to implement a stack.

Python data-structures tutorial | Java ArrayList documentation

MATCH THE COLLECTION OPERATION

Terminology

Terminology

Collection

A group of entries organised for access and processing.

Element

One entry in a collection.

One-dimensional structure

A structure where one index selects an element.

Two-dimensional structure

A logical arrangement addressed by two coordinates, such as row and column.

Index

A position used to select an entry.

Zero-based indexing

Numbering entries starting at index 0.

List literal

Python square-bracket notation creating a list from written entries.

Empty list

A Python list with zero entries, written [].

Length

The number of entries in the selected collection.

Indexed assignment

Replacing the value at an existing selected position.

Append

Add one entry at the logical end.

Insert

Add an entry before a position, shifting later entries.

Remove by value

Delete an equal entry, such as Python remove deleting the first match.

Positional removal

Remove the entry at a selected index.

pop

Python list operation removing and returning an entry, last by default.

Traversal

Visiting a collection’s entries in a defined order.

Value loop

A loop receiving each entry value rather than its index.

Index loop

A loop using positions to read or update stored entries.

Filter

Select entries satisfying a condition into a result.

Accumulator

A value retaining a running result through iterations.

Row

An inner collection in this lesson’s row-first 2D representation.

Column

A position within a row in a rectangular grid.

Nested loop

A loop whose body contains another loop.

Row-major traversal

Here, visiting all columns of a row before moving to the next row.

Rectangular grid

A 2D arrangement whose rows all have the same length.

Ragged structure

A nested arrangement with rows of unequal lengths.

Aliasing

Multiple references reaching the same mutable object.

Shallow copy

A new outer collection containing references to the same nested objects.

Independent rows

Distinct row objects that do not share one mutable row by construction.

ArrayList

Java’s dynamic array-style collection using methods such as add/get/set.

Java array

An indexed structure whose own length remains fixed after creation.

Generic type argument

The element reference type specified in Java notation such as ArrayList<Integer>.

Overload

Same method name with different parameter signatures, such as Java remove(int) and remove(Object).

Mutation

Changing the contents of an existing mutable object.

Return value

A value supplied to the caller, such as the entry returned by pop.

Boundary check

A condition confirming a position or value is inside the required limits.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe indexes?
2. Which distinguish insertion and replacement?
3. Which describe Python removal?
4. Which describe append?
5. Which traversals are appropriate?
6. Which describe Java ArrayList?
7. Which describe grid=[[4,7,2],[5,1,6]]?
8. Which support nested traversal?
9. Which prevent shared-row surprises?
10. Which handle empty input deliberately?
11. Which describe Java integer removal?
12. Which improve tests?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Construct a Python list program that appends15, inserts14 at index1 and replaces index0 with10.

2. Trace remove(12) then pop(1) on [12,18,12,15].

3. Construct an indexed loop adding one to every score.

4. Construct a total and average with an empty-list check.

5. Construct a filter collecting scores at least15 without changing the source.

6. Describe the corresponding add, get, set and size operations in Java ArrayList.

7. Construct a Python 2D list and update row1,column2 to9.

8. Construct nested loops calculating the grand total of the grid.

9. Explain where to initialise row_total versus grand_total.

10. Explain why [[0]*3]*2 creates a shared-row problem.

11. Construct a Java 2D array traversal in outline.

12. Explain why a shallow outer copy of a nested list may still share updates.

CONSTRUCT IT | STUDENT RESULTS

Construct a program storing two students and three test scores per student using [[12,18,15],[10,20,15]]. Print each student total and average, then the grand total. Use row and column indexes and explain where each accumulator starts. Add tests that reveal swapped coordinates or an incorrectly reset grand total.

Reveal the expected results

Row totals are45 and45; row averages are15.0 and15.0; grand total90. Initialise each row total inside the outer loop and grand total before it. To expose coordinate mistakes use a second test with unequal row totals and distinct cells, because equal totals can hide some errors.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B2.2.2 Arrays and Lists is coming soon. Complete the matching task and written questions in your exercise book.