Python Foundations

Lists

Create, access, modify and loop through lists (the Python array) — declaring, indexing, append/insert/remove, traversal, counting, totalling, max/min/average, linear search, frequency, duplicates, and swapping. The foundation of almost every Paper 4 algorithm.

4.1 Declaring & Initialising a List

A list in Python is the practical version of an array in Cambridge pseudocode. You will use lists every time a question asks you to store a collection of items — names, marks, temperatures, queue contents — and process them one by one.

# A list of integers
numbers = [10, 20, 30, 40, 50]

# Mixed types are allowed (rare in Paper 4 but legal)
mixed = [5, "hello", 3.14, True]

# An empty list — items added later
empty = []
The fixed-size pattern:
  • When pseudocode gives you ARRAY[1:N], the safest Python equivalent is myList = [0] * N (for integers) or myList = ["" for i in range(N)] (for strings).
  • This pre-fills the list so indexing never goes out of range.
# Fixed size of 10, pre-filled with zeros
scores = [0] * 10

# Fixed size of 20, pre-filled with empty strings
queueData = ["" for i in range(20)]
Exam tip:
  • Paper 4 mark schemes reward visible structure.
  • Always create your list on its own line before you use it — examiners want to see the declaration step exists separately from the processing step.
  • One line per logical action.
Your Turn — Declaring and accessing a list [3 marks]
A teacher needs to store the marks of 5 students. Write Python code that declares a list called marks initialised with the values 72, 85, 60, 91, 48. Then print the third mark.
Hint:
  • "Third" means index 2 (Python counts from 0)
  • Lists are zero-indexed
Your Turn [3 marks]
A shop records the prices of 5 products as 120, 85, 200, 45, 310. Write Python code that declares a list called prices with these values, then prints the fourth price.
Hint:
  • Lists are zero-indexed
  • Fourth element is at index 3 (not 4)

4.2 Accessing & Modifying Items

Python indexing starts at 0 for the first item. Negative indices count from the end — -1 is the last item, -2 the second-to-last. Lists are mutable: you can replace, add or remove items.

Item1020304050
Positive index01234
Negative index-5-4-3-2-1

Reading & changing

numbers = [10, 20, 30, 40, 50]

print(numbers[0])   # 10  → first
print(numbers[2])   # 30  → third
print(numbers[-1])  # 50  → last
print(numbers[-2])  # 40  → second-to-last

# Replace an item (lists are mutable)
numbers[1] = 25
print(numbers)      # [10, 25, 30, 40, 50]

Adding & removing

fruits = ["apple", "banana"]
fruits.append("mango")      # end → ["apple","banana","mango"]
fruits.insert(1, "orange")  # idx 1 → ["apple","orange","banana","mango"]

fruits.remove("orange")  # first match
last = fruits.pop()       # remove+return last (stack pop)
print(len(fruits))        # number of items
Length vs last index:
  • If a list has n items, the valid indices are 0 to n − 1.
  • So len(marks) is 5, but marks[5] is an error.
  • This off-by-one mistake is the most common cause of IndexError crashes in Paper 4.
Exam tip:
  • When a question says "the nth item", always convert it in your head to "index n − 1" before you write code.
  • Writing the wrong index is the single most common Paper 4 list error and almost never earns the mark.
Your Turn — Accessing and modifying list items [3 marks]
A hospital stores 6 patient temperatures as temps = [36.5, 37.2, 38.1, 36.9, 39.0, 37.5]. Write Python code that: (a) replaces the third temperature with 37.0 [1] (b) appends a new reading 36.8 to the end [1] (c) prints the number of recorded temperatures [1]
Your Turn [3 marks]
A library stores 6 book IDs as books = [101, 205, 318, 422, 519, 630]. Write Python code that: (a) replaces the fifth book ID with 525 [1] (b) appends a new book ID 701 [1] (c) prints the total number of book IDs in the list [1]
Hint:
  • Lists are zero-indexed
  • Fifth item is at index 4

4.3 Traversing a List

Almost every Paper 4 list question needs you to visit every element. That visiting process is called traversal, and there are exactly two ways to do it in Python — you need both.

Form 1 — Direct loop (values only)

numbers = [10, 20, 30, 40, 50]
for num in numbers:
    print(num)
# num is each list item in turn.
# Use when you do NOT need the index.

Form 2 — Index loop (positions / modify)

numbers = [10, 20, 30, 40, 50]
for i in range(len(numbers)):
    print("Item at index", i, "is", numbers[i])
# range(len(...)) gives 0, 1, 2, 3, 4 —
# every valid index. Use to modify items
# (numbers[i] = ...) or report positions.
Pseudocode ↔ Python index mapping:
  • Pseudocode often uses bounds 1 TO N; Python's range(N) produces 0 TO N − 1.
  • Translate the algorithm, not the bounds — the logic stays the same, only the starting index differs.
Exam tip:
  • Examiners give marks for the right kind of loop, not just any loop.
  • If the question implies positions ("which student", "at what index"), use the index form — even if the direct form also produces the right output.
  • Picking the form that matches the question shows you understand why, not just how.
Your Turn — Traversing with index loop [4 marks]
A list scores = [45, 72, 88, 30, 55] stores test scores. Write Python code using a for loop with index, that prints each score and its position number (starting from 1, not 0) in the format Student 1: 45.
Hint:
  • Day numbering starts at 1
  • List index starts at 0
  • Adjust by adding 1 to the index
Your Turn [4 marks]
A list temps = [22, 25, 19, 30, 28] stores daily temperatures for one week (5 days). Write Python code using a for loop with index that prints each temperature with the day number, in the format Day 1: 22.
Hint:
  • Day numbering starts at 1
  • List index starts at 0
  • Adjust by adding 1 to the index

4.4 Counting & Totalling

"How many?" and "what is the total?" are the two most common Paper 4 sub-questions. Both use the accumulator pattern: a variable that starts at zero before the loop, gets updated inside the loop, and is printed after the loop.

Initialise before, output after — never inside:
  • If you initialise inside the loop, the value resets every iteration (wrong answer).
  • If you output inside the loop, you print every partial result (wrong output).
  • Order matters.

Totalling a list

marks = [56, 78, 45, 90, 33]
total = 0                  # BEFORE
for m in marks:
    total = total + m      # INSIDE
print("Total:", total)     # AFTER

Conditional counting (passes)

marks = [56, 78, 45, 90, 33]
passes = 0
for m in marks:
    if m >= 50:
        passes = passes + 1
print("Passes:", passes)
Exam tip:
  • Cambridge mark schemes typically award a mark for the correct initialisation, a mark for the correct update inside the loop, and a mark for the output after the loop.
  • That is three marks just for following the pattern — skipping the init line loses a free mark.
Your Turn — Counting and totalling [5 marks]
A school records the daily attendance counts for one week (5 days) in the list attendance = [180, 175, 182, 168, 190]. Write Python code that calculates and outputs (a) the total attendance, and (b) the number of days where attendance was 180 or more.
Hint:
  • Use one loop with two accumulators
  • Initialise both accumulators before the loop starts
  • Update both inside the loop body
Your Turn [5 marks]
A delivery company records the parcel counts for one week (5 days) in parcels = [42, 38, 55, 27, 60]. Write Python code that calculates and outputs (a) the total parcels for the week, and (b) the number of days on which 40 or more parcels were delivered.
Hint:
  • Use one loop with two accumulators
  • Initialise both accumulators before the loop starts
  • Update both inside the loop body

4.5 Maximum, Minimum & Average

Finding the highest mark, the coldest temperature, or the average speed are stock Paper 4 questions. To find a max or min you cannot start the tracker at 0 — if all the values are negative, the answer would wrongly come out as 0. Start at the first element instead.

Why start at list[0]?
  • Starting at list[0] guarantees the tracker holds a real value from the list.
  • Starting at 0 assumes data you do not have.
  • The exam will sometimes give negative values, decimals, or all-equal lists to catch students who started at 0.
# Max, min AND average in ONE traversal
values = [12, 45, 7, 89, 3, 22]
maxValue = values[0]   # start with the first element
minValue = values[0]
total = 0
for v in values:
    if v > maxValue:
        maxValue = v
    if v < minValue:
        minValue = v
    total = total + v
average = total / len(values)
print("Max:", maxValue)
print("Min:", minValue)
print("Average:", round(average, 2))
Exam tip:
  • Do not use Python's built-in max(), min(), or sum() when the question says "write an algorithm to find…".
  • The mark scheme awards marks for the comparison logic inside the loop.
  • Built-ins skip the logic and earn zero method marks.
Your Turn — Maximum, minimum and average [6 marks]
A weather station records 7 daily temperatures in temps = [15, 21, 19, 8, 10, 27, 33]. Write Python code that outputs the highest temperature, the lowest temperature, and the average temperature (to 2 decimal places).
Hint:
  • Initialise maxT and minT using temps[0] (not 0)
  • Initialise total using 0
  • Update all three inside the loop
Your Turn [6 marks]
A factory records 7 daily production counts in output = [120, 95, 140, 88, 110, 130, 105]. Write Python code that outputs the highest output, the lowest output, and the average output (to 2 decimal places).
Hint:
  • Initialise maxOut and minOut using output[0] (not 0)
  • Initialise total using 0
  • Update all three inside the loop

4.6 Linear Search & Frequency

Linear search is a guaranteed Paper 4 question type. The 9618 syllabus says you must write the algorithm — you cannot just use Python's in operator.

Syllabus rule — must write your own search:
  • When a 9618 question asks you to implement a linear search, you must manually loop through the list and compare each element.
  • Using in, index(), or count() will not earn the method marks.

The found-flag pattern

items = [3, 8, 6, 12, 9]
target = 6

found = False       # assume not found
position = -1       # sentinel: "no valid position"
for i in range(len(items)):
    if items[i] == target:
        found = True
        position = i
        break         # stop on first match

if found:
    print("Found at index", position)
else:
    print("Not found")
  • found starts False — we assume not found until proven otherwise.
  • position = -1 is a sentinel meaning "no valid position" (list indices are never negative).
  • break exits as soon as the target is found — without it, a duplicate target would overwrite position.
Exam tip:
  • Even when the target is guaranteed to exist, still write the else branch.
  • The mark scheme awards an explicit mark for handling the "not found" case.
  • Skipping it loses that mark.

Frequency count (conditional counter)

nums = [4, 1, 4, 6, 4, 7, 2]
target = 4
count = 0
for n in nums:
    if n == target:
        count = count + 1
print("Frequency of", target, ":", count)
# Output: Frequency of 4 : 3
Your Turn — Linear search [6 marks]
A list studentIDs = [4521, 7832, 1209, 6604, 3318] stores student ID numbers. Write a Python program that uses a linear search to look for the ID 6604 and outputs either the index where it was found or the message "ID not in list". Do not use Python’s in keyword.
Hint:
  • Assume not found (flag = False) before the loop
  • Update the flag and the position inside the if block
  • Use break to stop on the first match
Your Turn [6 marks]
A list productCodes = [105, 220, 318, 422, 519] stores product codes. Write a Python program that uses a linear search to find the code 318 and outputs either the index where it was found or the message "Code not in list". Do not use Python’s in keyword.
Hint:
  • Assume not found (flag = False) before the loop
  • Update the flag and the position inside the if block
  • Use break to stop on the first match

4.7 Removing Duplicates (Unique List)

Building a duplicate-free copy of a list is the first algorithm on this page that uses a nested loop: an outer loop over the original list, and an inner loop over the unique list being built.

original = [1, 2, 2, 3, 4, 4, 1]
unique = []
for item in original:
    # Manual "is it already there?" check
    alreadyIn = False
    for u in unique:
        if u == item:
            alreadyIn = True
            break
    if not alreadyIn:
        unique.append(item)
print("Unique:", unique)
# Output: Unique: [1, 2, 3, 4]
Two loops — and that is fine:
  • Examiners expect to see the nested loop here.
  • The shortcut if item not in unique would work but uses the in operator — avoid it when the question requires you to write the search yourself.
Exam tip:
  • When the question says "produce a list of unique values", the mark scheme requires a new list, not a modified original.
  • Modifying the original list while looping through it causes index errors and is almost always penalised.
Your Turn — Frequency and removing duplicates [7 marks]
A list colors = ["red", "blue", "red", "green", "blue", "red"] contains the colours chosen by students. Write Python code that outputs (a) the number of times "red" appears, and (b) a list of unique colours (each colour listed once only). Do not use in, count() or set().
Hint:
  • Use the same two-step structure
  • Step 1: one accumulator for the count
  • Step 2: a nested loop to build the unique list
Your Turn [7 marks]
A list grades = ["A", "B", "A", "C", "B", "A", "D"] contains student grades. Write Python code that outputs (a) the number of times "A" appears, and (b) a list of unique grades (each grade listed once only). Do not use in, count() or set().
Hint:
  • Use the same two-step structure
  • Step 1: one accumulator for the count
  • Step 2: a nested loop to build the unique list

4.8 Swapping Elements

Every sorting algorithm in Paper 4 — bubble sort, insertion sort — is built on top of swapping two elements. To swap safely you need a temporary variable to hold one value while the other is overwritten.

values = [1, 2, 3, 4, 5]
temp = values[0]          # 1. SAVE the first value
values[0] = values[-1]    # 2. OVERWRITE first with last
values[-1] = temp         # 3. RESTORE saved value into last
print(values)             # [5, 2, 3, 4, 1]
Why a temp variable is needed:
  • Doing values[0] = values[-1] first destroys the original value at index 0.
  • If you then write values[-1] = values[0], both elements end up the same.
  • The temp variable stores the soon-to-be-destroyed value so it can be put back in the right place.
Exam tip:
  • Python lets you swap on one line with tuple unpacking — values[0], values[-1] = values[-1], values[0] — but Paper 4 mark schemes traditionally expect the three-step version because it mirrors the Cambridge pseudocode pattern PROCEDURE SWAP(BYREF X, Y).
  • Use the three-step form unless the question explicitly allows Python idioms.
Exam tip:
  • The three swap lines are usually awarded one mark each — and the order matters.
  • Writing them in the wrong order loses the mark even if the code happens to work for some inputs.
  • Make the order automatic: save, overwrite, restore.
Your Turn — Swapping first and last with a temp variable [3 marks]
A list letters = ['a', 'b', 'c', 'd', 'e'] stores letter codes. Write Python code, using a temporary variable, that swaps the first and the last element. Then output the modified list. Do not use tuple unpacking.
Hint:
  • Save the first value to a temp variable
  • Overwrite first with the last value
  • Restore the saved value using temp
Your Turn [3 marks]
A list names = ['Sara', 'Aman', 'Reha', 'Imran', 'Zara'] stores names. Write Python code, using a temporary variable, that swaps the first and the last element, then outputs the modified list. Do not use tuple unpacking.
Hint:
  • Save the first value to a temp variable
  • Overwrite first with the last value
  • Restore the saved value using temp

4.9 Mixed Paper 4 Tasks

These tasks combine the skills from 4.1–4.8 into compound questions you will meet in the real Paper 4.

Your Turn — Task A — Positive, negative and zero counts [5 marks]
Write a Python program that counts how many values in the list values = [-2, 4, 0, 0, -7, 8, 1, -3, 0, 5] are positive, negative and zero, and outputs the three counts.
Hint:
  • Use three accumulators
  • All start at 0
  • All updated inside one loop
Your Turn — Task B — Average of values meeting a condition [5 marks]
A list ages = [18, 22, 20, 19, 23] stores ages. Write a Python program that calculates and outputs the average age of those who are 20 or older.
Hint:
  • Keep two accumulators: total of qualifying ages and a count
  • Only add when the age qualifies
  • Divide total by count at the end
Your Turn — Task C — Sum of values above a threshold [3 marks]
A list nums = [5, 25, 30, 15, 50] stores numbers. Write a Python program that calculates and outputs the total of all values greater than 20.
Hint:
  • Use a conditional accumulator
  • Only add when the value passes the check
  • Initialise the accumulator to 0 before the loop
Your Turn — Task D — Even and odd counts [4 marks]
A list nums = [11, 14, 18, 21, 5, 3] stores integers. Write a Python program that counts and outputs how many are even and how many are odd.
Hint:
  • Use % 2 to find the remainder
  • Remainder 0 means the number is even
  • Otherwise the number is odd
The 5-step template for every list question:
  • Almost every Paper 4 list question rewards the same structure: initialise variables → declare/receive the list → write the loop → update inside the loop → output after the loop.
  • Make this your default mental template.
  • Identify the type of accumulator (count, sum, max/min, search flag, swap-temp) first; then drop the right pattern into the template.

4.10 Practice Tasks

Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python solution.

1Practice Task — Creating lists [2 marks]
Create a Python list called fruits containing exactly these strings in order: apple, banana, cherry, date.
2Practice Task — Accessing elements [2 marks]
Given the list nums = [10, 20, 30, 40, 50], write Python statements to: (a) print the first element (b) print the last element using a negative index (c) print the third element
3Practice Task — Using len() [2 marks]
Given the list colours = ['red', 'green', 'blue', 'yellow', 'purple'], use the len() function to print how many items the list contains.
4Practice Task — Checking membership with in [3 marks]
Given the list vowels = ['a', 'e', 'i', 'o', 'u'], ask the user to enter a single character. Use the in operator to print "Vowel" if the character is in the list, or "Not a vowel" otherwise.
5Practice Task — Reversing a list [3 marks]
Given the list nums = [1, 2, 3, 4, 5], reverse the list WITHOUT using the built-in reverse() method. Print the reversed list. Use a loop to build a new list.
6Practice Task — Slicing [3 marks]
Given the list letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], write slice expressions to produce: (a) ['b', 'c', 'd'] (b) ['f', 'g', 'h'] (c) ['a', 'c', 'e', 'g'] (every second element)
7Practice Task — append / insert / remove [4 marks]
Starting with the list tasks = ['eat', 'sleep'], perform these operations in order: 1. Append 'code' to the end. 2. Insert 'read' at position 1. 3. Remove 'sleep' from the list. Print the final list.
8Practice Task — Looping through lists [3 marks]
Given the list names = ['Alice', 'Bob', 'Charlie', 'Diana'], use a for loop to print each name on a separate line, prefixed with "Hello, ".
9Practice Task — Counting occurrences [4 marks]
Given the list marks = [45, 78, 90, 45, 62, 45, 88, 78], write a Python program that counts and prints how many times the value 45 appears in the list. Do NOT use the built-in count() method.
10Practice Task — Summing elements [3 marks]
Given the list prices = [12.50, 8.00, 15.75, 22.00, 5.50], use a for loop to calculate and print the total of all prices. Do NOT use the built-in sum() function.
11Practice Task — List comprehension basics [4 marks]
Use a list comprehension to create a list of the squares of the numbers 1 through 10. Print the resulting list.
12Practice Task — Finding max and min [5 marks]
Given the list scores = [56, 89, 34, 92, 71, 45], write a Python program using a for loop that finds and prints BOTH the highest and lowest scores. Do NOT use the built-in max() or min() functions.
13Practice Task — 2D list basics [5 marks]
A 2D list represents a 3x3 grid of numbers: grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Write a Python program that uses nested for loops to: (a) print every number in the grid, one per line (b) calculate and print the total sum of all numbers
14Practice Task — Merging two sorted lists [6 marks]
You have two sorted lists: a = [1, 3, 5, 7] b = [2, 4, 6, 8, 10] Write a Python program that merges them into a single sorted list called merged, WITHOUT using the built-in sort() method or sorted() function. Print the final list.
15Practice Task — Full exam-style list question [8 marks]
A class of 6 students sat a test. Their names and scores are stored in two parallel lists: names = ['Sara', 'Aman', 'Reha', 'Imran', 'Zara', 'Bilal'] scores = [78, 92, 65, 88, 92, 73] Write a complete Python program that: 1. Calculates and prints the class average score. 2. Finds and prints the name(s) of the student(s) with the HIGHEST score (handle ties). 3. Counts and prints how many students scored above the average. Do NOT use built-in max(), min(), or sum() functions.

Key Points Summary

Lists use [ ] — the Python equivalent of a pseudocode ARRAY. Fixed size: [0]*N or ["" for i in range(N)].
Zero-based indexing: first item is list[0]. Negative indices count from the end (-1 is last).
len(list) gives the count; valid indices are 0 to len-1. list[len] is an IndexError.
append(x) adds to the end; insert(i, x) at index i; remove(x) and pop(i) take items out.
Direct loop "for item in list" for values; index loop "for i in range(len(list))" for positions/modification.
Accumulator pattern: initialise BEFORE, update INSIDE, output AFTER — never inside.
Max/min trackers start at list[0] (not 0) to handle all-negative lists.
Never use built-in max()/min()/sum() when asked to "write an algorithm" — write the loop.
Linear search: found flag + position (-1 sentinel) + break on first match. No "in" operator.
Removing duplicates uses a nested loop (outer over original, inner over unique being built).
Swap with 3 steps: temp = a, a = b, b = temp. Order matters — save, overwrite, restore.
5-step template: init → declare list → loop → update inside → output after.

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

Question 1Multiple Choice

Which line creates a Python list of 5 integers?

Question 2True / False

In nums = [10, 20, 30, 40, 50], nums[5] returns the last item (50).

Question 3Multiple Choice

What does append(x) do?

Question 4Multiple Choice

Which loop form is correct when you need to MODIFY list items by index?

Question 5True / False

An accumulator (like total) must be initialised BEFORE the loop and printed AFTER the loop.

Question 6Multiple Choice

Why do max/min trackers start at list[0] rather than 0?

Question 7Multiple Choice

In a linear search, what is the starting value of the `found` flag?

Question 8True / False

Using Python's built-in max() earns full marks when the question says "write an algorithm to find the maximum".

Question 9Multiple Choice

What is the output? nums = [4, 1, 4, 6, 4, 7, 2] count = 0 for n in nums: if n == 4: count += 1 print(count)

Question 10Multiple Choice

To swap two list elements safely, you need a temporary variable. What is the correct 3-step order?

Question 11True / False

When building a unique-values list, you should modify the original list while looping through it.

Question 12Multiple Choice

Which is the standard 5-step template for almost every Paper 4 list question?

Answer all 12 questions to enable submission.