SDD  ·  Software Design & Development

Arrays

Lesson 12 of 19 Approx 60 min Requires: SDD9 Fixed Loops, SDD11 Predefined Functions 🚀 Extension Studio
Learning intentions
  • Understand what an array is and why it is used instead of separate variables
  • Create and access elements in an array using index notation, starting at index 0
  • Use arrays with FOR loops to traverse and process multiple values efficiently
Success criteria
  • I can explain what an array is and state why it is more efficient than using separate variables
  • I can create an array in Python and access individual elements using their index number
  • I can update an element in an array by assigning a new value to a specific index
  • I can use len() to find the number of elements in an array
  • I can use a FOR loop with range(len(array)) to traverse all elements of an array
  • I can read and trace SQA reference language for array creation, element access, and traversal
Warm up — what do you already know?

Answer before the lesson begins. These check prior knowledge from earlier lessons — it's fine if you're unsure.

1. A program needs to store the test scores of 5 pupils separately. How many variables would be needed if an array is NOT used?

2. A Python FOR loop begins: for index in range(5):. What values does index take during the loop?

3. What does len("hello") return?

Key vocabulary

array
A variable that stores multiple values of the same data type under one name. Each value is accessed using an index number.
index
The position of an element within an array. Indexing starts at 0 in Python — the first element is at index 0, the second at index 1, and so on.
element
A single value stored in an array. An array with five values has five elements, each at a different index.
traverse
To go through each element of an array one at a time, usually using a FOR loop. Traversal is used for tasks like calculating totals or finding the highest value.
list
Python's built-in name for a collection of values in square brackets. In N5 Computing Science, lists are used as arrays. The terms are interchangeable for this course.
out of bounds
Trying to access an index that does not exist in the array. For example, accessing index 5 in a 5-element array (which only has indices 0–4) causes an IndexError.

Arrays

Why use arrays?

Imagine a program that stores the test scores of 30 pupils. Without arrays, you would need 30 separate variables: score1, score2, score3, … score30. Adding them all up would require writing every variable name out explicitly — a long expression to calculate a total. If the number of pupils changed, you would have to rewrite large parts of the program.

Arrays solve this problem. An array stores multiple values of the same data type under one name. A loop can then process all the values without naming each one individually. This makes programs shorter, easier to maintain, and straightforward to extend.

Creating an array in Python

In Python, arrays are implemented as lists. A list is created using square brackets with values separated by commas:

scores = [85, 72, 91, 68, 88]

This creates an array called scores containing 5 integer values. For N5 Computing Science, all elements in an array should be the same data type — integers, real numbers (floats), or strings.

scores = [85, 72, 91, 68, 88] 85 72 91 68 88 index → 0 1 2 3 4 scores[2] = 91 The third element — index 2 is position 3 (counting starts at 0)

Accessing elements — index notation

Each element has an index number starting at 0. To read an element, write the array name followed by the index in square brackets:

Element8572916888
Index01234
scores[0]   # 85  — first element
scores[1]   # 72  — second element
scores[4]   # 88  — fifth (last) element

The index of the first element is always 0. An array with n elements has indices 0 to n − 1. Check each index against the array before tracing the program.

Updating elements

You can change the value at a specific index by assigning a new value to it:

scores[2] = 95   # changes the third element from 91 to 95

After this line, the array becomes [85, 72, 95, 68, 88]. All other elements remain unchanged.

Finding the number of elements: len()

The len() function works on arrays just as it does on strings — it returns the number of elements:

len(scores)   # returns 5

This is especially useful in loops, because it means you do not have to know (or hard-code) the size of the array.

Traversing an array with a FOR loop

A key array operation is traversal — processing every element in order. Combine range() with len() to generate every valid index:

scores = [85, 72, 91, 68, 88]
for index in range(len(scores)):
    print(scores[index])

The variable index takes values 0, 1, 2, 3, 4 in turn. On each iteration, scores[index] reads the element at that index. The result is that every element is printed, in order.

iteration 1 index = 0 85 72 91 68 88 0 1 2 3 4 scores[0] → 85 iteration 2 index = 1 85 72 91 68 88 0 1 2 3 4 scores[1] → 72 iteration 3 index = 2 85 72 91 68 88 0 1 2 3 4 scores[2] → 91 …continues for index = 3 (prints 68) and index = 4 (prints 88)

A typical traversal accumulates a running total:

scores = [85, 72, 91, 68, 88]
total = 0
for index in range(len(scores)):
    total = total + scores[index]
print("Total:", total)

Always initialise the accumulator variable (here, total = 0) before the loop begins, or Python will raise a NameError when it tries to add to a variable that does not yet exist.

Combining traversal with selection

An if statement inside a loop allows you to process only certain elements:

scores = [85, 72, 91, 68, 88]
for index in range(len(scores)):
    if scores[index] >= 80:
        print("High score:", scores[index])

This prints only the elements that are 80 or above: 85, 91, and 88.

SQA reference language (read only)

SQA uses reference language in question papers. You need to be able to read it. You will never be asked to write it.

Read the reference-language column and compare each operation with Python. For a write-code task, use Python; for a design task, use structured-English pseudocode to describe the logic. Example 4 provides a reference-language trace.

OperationPythonSQA reference language (read only)
Create arrayscores = [85, 72, 91]SET scores TO [85, 72, 91]
Access elementscores[0]scores[0]
Update elementscores[2] = 95SET scores[2] TO 95
Traversefor index in range(len(scores)):FOR index FROM 0 TO LEN(scores) - 1 DO

When reading this indexed reference-language loop, note its inclusive upper bound: LEN(scores) - 1, not LEN(scores). For a 5-element array, the loop runs from 0 to 4 — going up to 5 would attempt to access an index that does not exist. Python range(len(scores)) stops before 5, so it visits the same indices 0, 1, 2, 3, 4.

Worked examples

Example 1 — Creating an array and accessing elements

A program stores the daily maximum temperatures (°C) for a week: 15, 18, 14, 20, 17, 16, 13. Display the temperature for Monday (first day) and Thursday (fourth day).

1
Create the array: temps = [15, 18, 14, 20, 17, 16, 13]. There are 7 elements, so indices run from 0 (Monday) to 6 (Sunday).
2
Access Monday: Monday is the first day — index 0. temps[0] = 15.
3
Access Thursday: Thursday is the fourth day — index 3. temps[3] = 20.
temps = [15, 18, 14, 20, 17, 16, 13]
print("Monday:   ", temps[0])
print("Thursday: ", temps[3])
Output: Monday: 15 Thursday: 20
Example 2 — Updating an element and calculating the total

Marks for 4 pupils are stored as [62, 78, 54, 91]. The third pupil's mark is corrected to 69 after an appeal. Calculate and display the new total.

1
Update element: The third pupil is at index 2. marks[2] = 69 changes 54 to 69. Array is now [62, 78, 69, 91].
2
Traverse to calculate total: Initialise total = 0 before the loop, then add each element in turn.
3
Python code and trace:
marks = [62, 78, 54, 91]
marks[2] = 69
total = 0
for index in range(len(marks)):
    total = total + marks[index]
print("Total:", total)
Trace: index=0 → total=62; index=1 → total=140; index=2 → total=209; index=3 → total=300. Output: Total: 300. Verified: 62 + 78 + 69 + 91 = 300 ✓
Example 3 — Traversal with selection: finding pass scores

Five exam scores are stored: [45, 72, 38, 88, 61]. Display only the scores that are a pass (50 or above).

1
Plan: Traverse the array. For each element, use an if statement to check whether it is ≥ 50. Only print it if the condition is true.
2
Python code:
scores = [45, 72, 38, 88, 61]
for index in range(len(scores)):
    if scores[index] >= 50:
        print("Pass:", scores[index])
3
Trace: index=0: 45 < 50 — skipped. index=1: 72 ≥ 50 — prints Pass: 72. index=2: 38 < 50 — skipped. index=3: 88 ≥ 50 — prints Pass: 88. index=4: 61 ≥ 50 — prints Pass: 61.
Example 4 — SQA reference language (read only)

An array called prices holds 6 real numbers: [12.99, 8.50, 24.99, 6.75, 15.00, 3.49]. Read and trace the reference language below to calculate the final total and state how many iterations run.

1
Read the reference-language structure: Read SET ... TO [...] to create the array. Read FOR index FROM 0 TO LEN(prices) - 1 DO for the loop — the upper bound is 5 (6 elements, indices 0–5).
2
SQA reference language (read only):
SET prices TO [12.99, 8.50, 24.99, 6.75, 15.00, 3.49]
SET total TO 0
FOR index FROM 0 TO LEN(prices) - 1 DO
    SET total TO total + prices[index]
END FOR
SEND "Total: " & total TO DISPLAY
3
Verify the trace: After indices 0, 1, 2, 3, 4, 5, the total is 12.99, 21.49, 46.48, 53.23, 68.23, 71.72. Final output: Total: 71.72 ✓. The loop runs 6 times (index 0 to 5). Using LEN(prices) - 1 rather than a hard-coded 5 means the reference-language loop still works correctly if the array size changes.
Now you try

A program uses an array to store the number of goals scored by a football team in each of their 5 matches: 2, 0, 3, 1, 4.

Answer the following:

  1. Write the Python code to declare this array.
  2. What is the value of goals[3]?
  3. Write the Python code to calculate and print the total number of goals scored.
  1. goals = [2, 0, 3, 1, 4]
  2. goals[3] = 1. Index 3 is the fourth element (2 is at index 0, 0 at index 1, 3 at index 2, 1 at index 3).
  3. goals = [2, 0, 3, 1, 4]
    total = 0
    for index in range(len(goals)):
        total = total + goals[index]
    print("Total goals:", total)
    Trace: 0+2=2, 2+0=2, 2+3=5, 5+1=6, 6+4=10. Output: Total goals: 10. Verified: 2+0+3+1+4=10 ✓
Common mistakes
✕
Using index 1 for the first element. The first element is always at index 0, not index 1. Writing scores[1] accesses the second element. This off-by-one error can produce a wrong answer in a trace question without any error message from Python.
✕
Going out of bounds. For an array with 5 elements, the valid indices are 0, 1, 2, 3, 4. Trying to access scores[5] causes an IndexError: list index out of range. This often happens when a loop uses range(len(scores) + 1) instead of range(len(scores)), or when a reference-language loop uses FOR index FROM 0 TO LEN(array) instead of LEN(array) - 1.
✕
Starting the loop at index 1. Writing for index in range(1, len(scores)): skips the first element (index 0). The total will be wrong, and no error is raised, making this a difficult bug to spot. The correct form is range(len(scores)) which starts at 0 automatically.
✕
Forgetting to initialise the accumulator. Writing a loop that does total = total + scores[index] without first declaring total = 0 causes a NameError — Python cannot add to a variable that does not yet exist. Always set accumulator variables to 0 (for totals) before the loop begins.
✕
Using round brackets instead of square brackets. Writing scores = (85, 72, 91) creates a tuple, not a list/array. Tuples look similar but behave differently — in particular, you cannot update individual elements. Always use square brackets [ ] when creating an array in Python.
Exam tip

Check the array indices and actual loop bounds when tracing. The first element of these arrays is at index 0, but begin the trace at the starting value given in the loop. If asked to give the value of names[2] for the array ["Alice", "Bob", "Charlie", "David"], the answer is "Charlie" — it is the third element, at index 2.

For these zero-based indexed reference-language loops, TO LEN(array) - 1 includes the last valid index. A bound of TO LEN(array) goes out of bounds. Python range(len(array)) stops before the length. A collection loop such as for value in array: is also a valid way to visit every value: choose a loop that solves the task.

When a question asks you to find a total, average, or count using an array, the structure is always the same: initialise the accumulator before the loop, update it inside the loop, and use the result after the loop ends.

Task Set

Questions 1–5 are auto-checked. Questions 6–8 are self-marked — write your answer, then reveal the model answer to check your work. Questions 9–10 are practical PyCharm implementation tasks.

1. Which of the following correctly creates an array of three integers called ages in Python? TYPE 1

2. An array is declared as temps = [18, 22, 15, 20, 17]. What does temps[3] return? TYPE 1

3. An array has 8 elements. What is the index of the last element? TYPE 1

4. Which code correctly traverses all elements of an array called values using a FOR loop? TYPE 1

5. What does the following code output?
numbers = [10, 20, 30, 40, 50]
total = 0
for index in range(len(numbers)):
    total = total + numbers[index]
print(total)
TYPE 1

6. An array heights = [162, 175, 158, 180, 170] stores the heights (cm) of 5 pupils. Write Python code to display only the heights that are 170 cm or more. TYPE 2

heights = [162, 175, 158, 180, 170]
for index in range(len(heights)):
    if heights[index] >= 170:
        print(heights[index])

Output: 175, 180, 170 (each on a separate line). The loop visits every element; the if statement filters out those below 170. Note that 170 is included because the condition uses >= (greater than or equal to), not >.

7. Write Python code for a program that: (a) creates an array of 4 integers called scores, (b) uses a FOR loop to receive each value from the keyboard, and (c) uses a second FOR loop to display each value. TYPE 2

Hint: Start with four zero values, use int(input(...)) to replace each one, then traverse the filled array in a separate loop.

scores = [0, 0, 0, 0]
for index in range(len(scores)):
    scores[index] = int(input("Enter score: "))
for index in range(len(scores)):
    print(scores[index])

With 4 elements, range(len(scores)) visits indices 0, 1, 2, 3. The first loop replaces each starting zero with an integer input; the second displays all four stored values. For inputs 12, 7, 0 and 18, the output is:

12
7
0
18

Any correct Python solution that stores four integers and then displays them using a second loop is valid; the display loop may visit the values directly.

8. The code below contains an error. Identify the error, explain what goes wrong when the program runs, and write the corrected code.
prices = [4.99, 2.50, 8.00, 1.25]
total = 0
for index in range(1, len(prices)):
    total = total + prices[index]
print("Total:", total)
TYPE 2

Error: The loop starts at index 1 instead of 0, so prices[0] (the value 4.99) is never added to total. No error message is produced — the code runs without crashing, but gives the wrong answer: 2.50 + 8.00 + 1.25 = 11.75 instead of the correct 16.74.

Corrected code:

prices = [4.99, 2.50, 8.00, 1.25]
total = 0
for index in range(len(prices)):
    total = total + prices[index]
print("Total:", round(total, 2))

Correct total: 4.99 + 2.50 + 8.00 + 1.25 = 16.74 ✓. Using range(len(prices)) starts at 0 automatically. round(total, 2) avoids displaying a long binary floating-point approximation; the output is Total: 16.74.

9. Practical: In PyCharm, create a new Python file called sdd12_arrays.py. Write a program that stores the temperatures [22, 18, 25, 20, 15], displays each temperature numbered from 1, then displays the average rounded to 1 decimal place. Run and record the complete output; then change the array to [10, 20, 30] and record that complete output too. TYPE 3

temps = [22, 18, 25, 20, 15]
for index in range(len(temps)):
    print("Temperature", index + 1, ":", temps[index])
total = 0
for index in range(len(temps)):
    total = total + temps[index]
average = round(total / len(temps), 1)
print("Average temperature:", average)

Exact expected output:

Temperature 1 : 22
Temperature 2 : 18
Temperature 3 : 25
Temperature 4 : 20
Temperature 5 : 15
Average temperature: 20.0

After changing the array to [10, 20, 30]:

Temperature 1 : 10
Temperature 2 : 20
Temperature 3 : 30
Average temperature: 20.0

Trace: total = 22+18+25+20+15 = 100. Average = 100 / 5 = 20.0. Note index + 1 gives display numbers 1 to 5 while the array indices remain 0 to 4.

10. Practical: In sdd12_arrays.py, replace the previous program with Python code that stores ["Alice", "Bob", "Charlie", "David"] and traverses the array to display each name on a new line. Test once with all four names and once after changing the array to ["Eva", "Finn"]. Record both outputs. TYPE 3

names = ["Alice", "Bob", "Charlie", "David"]
for index in range(len(names)):
    print(names[index])

Exact expected outputs:

Alice
Bob
Charlie
David

After changing the array to ["Eva", "Finn"]:

Eva
Finn

range(len(names)) automatically produces every valid index, so the same loop works for arrays of different lengths.

Teacher notes — Shift+T to hide

Suggested timing: 60 minutes. Warm up 10 min; notes + tables 15 min; worked examples 15 min; now you try 5 min; task set 15 min.

Key misconception to address: 0-based indexing. Virtually every pupil will at some point say "the first element is at index 1." Reinforce with a concrete analogy: house numbers in a row starting at 0 — the first house is number 0, the second is number 1. In a trace question, always write out the indices explicitly before starting: index 0 = first value, index 1 = second value, etc.

Live demo suggestion: Open a Python REPL. Create a list live — names = ["Alice", "Bob", "Charlie"]. Print names[0], names[1], names[2]. Then deliberately try names[3] to trigger an IndexError — pupils should see this error and know what causes it. Then show the traversal loop and the accumulator pattern. Finally demonstrate the off-by-one bug by changing range(len(names)) to range(1, len(names)) and asking pupils to predict what will be missed.

Extension question: Ask pupils to write a program that stores 5 test scores in an array, then counts how many are above the average. This combines traversal, accumulation, round() from SDD11, and a conditional counter — a good preparation for the standard algorithms in SDD13 and SDD14.

Note on Python for loops: Teach indexing for element access and updates, alongside collection loops such as for value in scores: for reading each value directly. The 2024 marking instructions, Q9(d) accept collection loops. An indexed spelling is not required for exam credit. Q7 is Python implementation; reference-language tables and Example 4 are for reading and tracing. Design answers use structured English, and any clear alternative design is valid.

SQA command words covered: "state" (Q2, Q3, Q10), "write" (Q6, Q7, Q9, Q10 Python), "identify" and "explain" (Q8 error).