Edexcel International Advanced Level Computer Science, point 8.1.2
This page is the practical (Unit 2) side of the structures you met in 4.2.1. You must be able to select and use one- and two-dimensional structures, treat lists as arrays, and convert between structures. Check the PLS for the exact detail.
a. Array (using a list)
Python's built-in list is used as an array. A fixed-size array can be made with a list of a set length.
scores = [0] * 5 # an array of 5 zeros
scores[2] = 90 # set by index
print(scores) # [0, 0, 90, 0, 0]
print(len(scores)) # 5
for i in range(len(scores)): # traverse by index
scores[i] = i * 10
Two-dimensional array (a list of lists)
grid = [[0] * 3 for _ in range(2)] # 2 rows, 3 columns of 0
grid[1][2] = 7 # row 1, column 2
print(grid) # [[0, 0, 0], [0, 0, 7]]
for r in range(2): # traverse all cells
for c in range(3):
print(grid[r][c], end=" ")
print()
Careful: [[0] * 3] * 2 makes two references to the same row, so changing one changes both. Build each row separately, as above.
b. List
A list can grow and shrink, and holds any types.
names = ["Amy", "Raj"]
names.append("Sam") # add to the end
names.insert(1, "Li") # insert at index 1
names.remove("Raj") # remove by value
last = names.pop() # remove and return the last
print(names, len(names))
print("Amy" in names) # membership -> True
names.sort() # sort in place
c. Dictionary
Key-value pairs. Keys are unique.
ages = {"Amy": 17, "Raj": 18}
ages["Sam"] = 16 # add
ages["Amy"] = 18 # update
print(ages["Raj"]) # retrieve -> 18
print(ages.get("Zed", "none")) # safe retrieve
del ages["Raj"] # delete
for key, value in ages.items(): # traverse
print(key, value)
A missing key with [] causes KeyError, so use get or check if key in ages.
d. Record
A record groups named fields of different types. In Python it is done with a class, a dictionary or a dataclass.
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
form: str
s = Student("Amy", 17, "12A")
s.age = 18 # update a field
print(s.name, s.age)
students = [s, Student("Raj", 18, "12B")] # a list of records
e. Tuple
Ordered and unchangeable.
point = (3, 4)
x, y = point # unpack
print(point[0]) # 3
# point[0] = 9 -> TypeError
f. Set
Unique items, no order.
tags = {"a", "b", "a"} # duplicates removed -> {"a", "b"}
tags.add("c")
tags.discard("a")
print("b" in tags) # True
Using a list as an array
The specification asks you to use lists as equivalent to arrays. An array (fixed size, one type) is represented by a list that you don't resize. So:
- One-dimensional:
a = [0] * n. - Two-dimensional: a list of lists, reached as
a[row][col].
Converting between structures
nums = [3, 1, 3, 2]
print(set(nums)) # list -> set: {1, 2, 3}
print(list(set(nums))) # set -> list (duplicates gone)
print(tuple(nums)) # list -> tuple: (3, 1, 3, 2)
print(list((1, 2))) # tuple -> list: [1, 2]
pairs = [("a", 1), ("b", 2)]
# list of pairs -> dict: {'a': 1, 'b': 2}
d = dict(pairs)
print(list(d.keys())) # dict keys -> list: ['a', 'b']
print(list(d.items())) # dict -> list of pairs
print(list("hello")) # string -> list of characters
print("".join(["h", "i"])) # list of strings -> string: 'hi'
Converting a list to a set loses duplicates and order.
Worked example
Task: a cinema stores its seating plan for 3 rows of 4 seats in a 2D array, where 1 means booked and 0 means free. Print how many seats are free in each row.
seats = [
[1, 1, 0, 1], # row 0
[0, 0, 0, 1], # row 1
[1, 1, 1, 1], # row 2
]
for row in range(3):
booked = 0
for col in range(4):
booked = booked + seats[row][col]
print("Row", row, "free seats:", 4 - booked)
Output: row 0 has 1 free seat, row 1 has 3, and row 2 has 0. The outer loop goes through the rows, the inner loop through the seats (columns) in that row, and seats[row][col] reads one cell.
Exam tip: know how to create, read, change, add and remove for each structure, and the index starts at 0. For a 2D array, the first index is the row and the second is the column. Pick the structure that fits (a dictionary to look up by name, a set for unique items), and say why.
Check yourself
How do you create an array of 10 zeros using a list?
[0] * 10.
What does grid[2][1] refer to in a 2D array?
The item in row 2 and column 1 (counting from 0).
What error does a missing dictionary key cause with square brackets?
KeyError.
What is the effect of converting a list to a set?
Duplicates are removed and the order is lost.
Why can't you change an item in a tuple?
Tuples are immutable: once created, their contents can't be altered.