- 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
- 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
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
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.
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:
| Element | 85 | 72 | 91 | 68 | 88 |
|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 |
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.
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.
| Operation | Python | SQA reference language (read only) |
|---|---|---|
| Create array | scores = [85, 72, 91] | SET scores TO [85, 72, 91] |
| Access element | scores[0] | scores[0] |
| Update element | scores[2] = 95 | SET scores[2] TO 95 |
| Traverse | for 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
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).
temps = [15, 18, 14, 20, 17, 16, 13]. There are 7 elements, so indices run from 0 (Monday) to 6 (Sunday).temps[0] = 15.temps[3] = 20.
temps = [15, 18, 14, 20, 17, 16, 13]
print("Monday: ", temps[0])
print("Thursday: ", temps[3])
Output:
Monday: 15
Thursday: 20Marks 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.
marks[2] = 69 changes 54 to 69. Array is now [62, 78, 69, 91].total = 0 before the loop, then add each element in turn.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 ✓Five exam scores are stored: [45, 72, 38, 88, 61]. Display only the scores that are a pass (50 or above).
if statement to check whether it is ≥ 50. Only print it if the condition is true.scores = [45, 72, 38, 88, 61]
for index in range(len(scores)):
if scores[index] >= 50:
print("Pass:", scores[index])Pass: 72. index=2: 38 < 50 — skipped. index=3: 88 ≥ 50 — prints Pass: 88. index=4: 61 ≥ 50 — prints Pass: 61.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.
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).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 DISPLAYTotal: 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.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:
- Write the Python code to declare this array.
- What is the value of
goals[3]? - Write the Python code to calculate and print the total number of goals scored.
goals = [2, 0, 3, 1, 4]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).-
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 ✓
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.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.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.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.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.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.
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
numbers = [10, 20, 30, 40, 50]
total = 0
for index in range(len(numbers)):
total = total + numbers[index]
print(total)
TYPE 16. 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.
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 2Error: 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.
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).