Edexcel International Advanced Level Computer Science, point 4.2.1
Definition and function
A data structure is a way of organising and storing a collection of data items so that they can be used efficiently. The right one makes a program simpler and faster. Here you need to understand them (and hand trace their operations). In Unit 2 you also create and use them in code (8.1.2, 8.2.4).
Static and dynamic
- A static data structure has a fixed size, set when it is created. Examples: an array and a tuple. Benefit: memory is reserved in advance, so access is fast and predictable. Drawback: it can't grow, and unused space is wasted.
- A dynamic data structure can grow and shrink while the program runs. Examples: a list, a dictionary and a set. Benefit: it uses only the memory it needs and can hold any number of items. Drawback: it can be slower, and needs extra memory to keep track of its items.
- A structure is mutable if its contents can be changed after it is created (a list), and immutable if they can't (a tuple).
a. Array
- Definition: a fixed-size, ordered collection of items, all of the same data type, reached by an index (position).
- Characteristics: size is set when created, items are stored next to each other in memory, index starts at 0, and access by index is very fast.
- Operation:
a[2]reads the third item.a[2] = 9replaces it. - Benefits: fast, direct access, memory-efficient.
- Drawbacks: fixed size (hard to add or remove items), one data type only.
- Dimensions: a one-dimensional array is a row. A two-dimensional array is a table (rows and columns), reached with two indices:
grid[row][col].
a = [4, 8, 15, 16] # used as a 1-D array
grid = [[1, 2, 3],
[4, 5, 6]] # 2-D: 2 rows, 3 columns
print(a[2]) # 15
print(grid[1][2]) # 6
b. List
- Definition: an ordered collection of items that can change in size. In Python it can hold mixed types.
- Characteristics: items are reached by index. Items can be appended, inserted, removed and changed.
- Benefits: flexible size, easy to use, mixed data allowed.
- Drawbacks: inserting or deleting in the middle is slow (items must shift), and a little more memory than an array.
names = ["Amy", "Raj"]
names.append("Sam") # ['Amy', 'Raj', 'Sam']
names.insert(1, "Li") # ['Amy', 'Li', 'Raj', 'Sam']
names.remove("Raj") # ['Amy', 'Li', 'Sam']
c. Dictionary
- Definition: a collection of key-value pairs. Items are found by key, not by position.
- Characteristics: keys are unique. Lookup by key is fast. Order isn't used to find items.
- Operation: a hash function turns the key into the position (index) where its pair is stored. To find, insert or delete a pair, the key is hashed to go straight to that position, with no searching through the other items.
- Benefits: very fast lookup by a meaningful key, and readable code.
- Drawbacks: uses more memory, and you need the key to find a value.
ages = {"Amy": 17, "Raj": 18}
ages["Sam"] = 16 # add
print(ages["Raj"]) # 18
del ages["Amy"] # remove
d. Record
- Definition: a single item made of several fields (attributes), which can have different data types.
- Characteristics: each field has a name:
student.name. It models one real-world thing. - Benefits: groups related data together, and keeps mixed types in one place.
- Drawbacks: fixed set of fields, and a collection of records needs a list or file.
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
form: str
s = Student("Amy", 17, "12A")
print(s.name) # Amy
(A record is similar to a row in a database table, 4.1.2.)
e. Tuple
- Definition: an ordered collection of items that can't be changed after it is created (immutable).
- Characteristics: reached by index, can hold mixed types, written with round brackets.
- Benefits: safe (can't be changed by mistake), slightly faster and smaller than a list, can be used as a dictionary key.
- Drawbacks: can't add, remove or change items (you must make a new tuple).
point = (3, 4)
print(point[0]) # 3
# point[0] = 5 -> error: a tuple can't be changed
f. Set
- Definition: an unordered collection of unique items (no duplicates).
- Characteristics: no index, no order, adding an item already there changes nothing. Membership tests are fast.
- Operations (common set operations):
| Operation | Meaning | Python |
|---|---|---|
| Union | Items in either set | A | B |
| Intersection | Items in both sets | A & B |
| Difference | Items in A but not B | A - B |
| Membership | Is an item in the set? | x in A |
| Add / remove | Change the set | A.add(x), A.remove(x) |
A = {1, 2, 3, 4}
B = {3, 4, 5}
print(A | B) # {1, 2, 3, 4, 5}
print(A & B) # {3, 4}
print(A - B) # {1, 2}
print(3 in A) # True
- Benefits: removes duplicates automatically, fast membership, set maths.
- Drawbacks: no order or index, only unique items.
Choosing a structure
| Need | Use |
|---|---|
| Fixed number of same-type items, fast index access | Array |
| Changing collection, in order | List |
| Look up by a name or ID | Dictionary |
| One thing with several named fields | Record |
| A fixed group that must not change | Tuple |
| Unique items, membership and set operations | Set |
Hand tracing operations
You may be asked to show the contents of a structure after a series of operations. Work one step at a time.
nums = [5, 2, 8]
nums.append(1) # [5, 2, 8, 1]
nums.insert(0, 9) # [9, 5, 2, 8, 1]
nums.remove(2) # [9, 5, 8, 1]
nums[1] = nums[3] # [9, 1, 8, 1]
For a 2-D array:
g = [[1, 2], [3, 4]]
g[0][1] = g[1][0] + g[1][1] # g[0][1] = 3 + 4 = 7
# g is now [[1, 7], [3, 4]]
To visit every item of a 2-D array, use a loop inside a loop: the outer loop takes each row, the inner loop each item in that row.
g = [[4, 0, 7], [2, 5, 1]]
total = 0
for row in g:
for value in row:
total = total + value
print(total) # 19
For a dictionary, assigning to a key that already exists changes its value, and del removes a pair:
stock = {"pen": 4, "cap": 9}
stock["lid"] = 2 # new key: {'pen': 4, 'cap': 9, 'lid': 2}
stock["pen"] = 6 # existing key: {'pen': 6, 'cap': 9, 'lid': 2}
del stock["cap"] # {'pen': 6, 'lid': 2}
print("cap" in stock) # False
# print(stock["cap"]) would now cause a KeyError
Worked example
Task: show the final contents of A and S after this code.
A = [3, 7, 7, 2]
S = set(A)
S.add(9)
S.add(7)
A[2] = 5
A.append(0)
S = set(A)removes duplicates: {2, 3, 7}.S.add(9): {2, 3, 7, 9}.S.add(7): already there, so unchanged: {2, 3, 7, 9}.A[2] = 5: A = [3, 7, 5, 2].A.append(0): A = [3, 7, 5, 2, 0].
Final: A = [3, 7, 5, 2, 0] and S = {2, 3, 7, 9}. Note that a set has no order, so the elements can be listed in any order.
Exam tip: know one benefit and one drawback of each structure, and choose with a reason ("a dictionary, because items are looked up by name"). When tracing, write the structure after every statement: assigning to an existing key changes its value (it doesn't add a second pair), and del removes the pair. Arrays and tuples are static; lists, dictionaries and sets are dynamic. Remember array and list indices start at 0, and that sets don't allow duplicates.
Check yourself
What is the difference between an array and a list?
An array has a fixed size and holds items of one type. A list can change size and (in Python) can hold different types.
Why is a tuple used instead of a list?
Its contents can't be changed, so it is safer when data must stay fixed, and it can be used as a dictionary key.
What is the intersection of {1, 2, 3} and {2, 3, 4}?
{2, 3}.
Which structure would you use to look up a product's price by its product code?
A dictionary, with the product code as the key and the price as the value.
How is a record different from an array?
A record groups several named fields that can have different data types, whereas an array holds many items of the same type reached by index.