OCR H446, section 1.4.2 (a)
A data structure is a way of organising a collection of data so that it can be used efficiently. This page covers four basic structures. Each stores several values under one name.
Arrays
An array is a collection of elements of the same data type, stored together, with each element reached by its index (its position). OCR pseudocode arrays are 0-based: the first index is 0.
array names[5]
names[0] = "Ahmad"
names[1] = "Ben"
names[2] = "Catherine"
print(names[1]) // Ben
- The size is usually fixed when the array is created (a static structure).
- Elements are stored next to each other in memory, so access by index is very fast.
- Looping through an array uses a
forloop and the index.
One-dimensional arrays
A single row of values. Useful for a list of marks, names or temperatures.
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Value | 72 | 58 | 91 | 66 |
Two-dimensional arrays
A grid (table) of rows and columns. Each element needs two indexes, here row, then column. In an exam question, read what each index stands for: the question sets it (the first index might be a card number, say, and the second one of its details).
array board[3,3]
board[0,0] = "X"
board[1,1] = "O"
print(board[1,1]) // O
| Col 0 | Col 1 | Col 2 | |
|---|---|---|---|
| Row 0 | X | ||
| Row 1 | O | ||
| Row 2 |
To visit every element, use nested loops:
for row = 0 to 2
for col = 0 to 2
print(board[row,col])
next col
next row
Uses: a game board, a spreadsheet, an image (rows and columns of pixels), a matrix.
Three-dimensional arrays
A cube of values, needing three indexes: for example temps[year, week, day]. Each element is a point in a 3D space. Uses: 3D models, a set of 2D images (like video frames), or data with three categories.
array temps[2,52,7] // 2 years, 52 weeks, 7 days
temps[0,10,3] = 14.5
Visiting every element needs three nested loops.
In Python
Python uses lists for arrays, and a 2D array is a list of lists:
grid = [[0] * 3 for _ in range(3)] # 3 by 3
grid[1][1] = 5
print(grid[1][1]) # 5
Records
A record is a collection of related fields, which can be different data types, treated as one item. It models one thing, such as a student.
// OCR's pseudocode guide has no record syntax, so this is generic
record Student
name string
year integer
average real
isPrefect boolean
endrecord
pupil = new Student
pupil.name = "Asha" // fields are reached with a dot
print(pupil.name)
There's no fixed record syntax in OCR's guide, and questions declare records in different styles. When a question uses records, it shows you the syntax. Fields are usually reached with dot notation: recordName.fieldName.
In Python, a record is often a class, a dictionary or a named tuple:
student = {"name": "Asha", "year": 12, "average": 71.5, "prefect": True}
print(student["name"]) # Asha
An array of records stores many such things: a table of data, as in a database (each record is one row, and each field is a column).
| Array | Record | |
|---|---|---|
| Elements are | All the same type | Can be different types |
| Accessed by | Index (a number) | Field name |
| Used for | A collection of similar items | One thing with several properties |
Records and classes
A record is close to a class (1.2.4 (e)), but simpler.
| Record | Class | |
|---|---|---|
| Groups related fields of different types under one name | Yes | Yes (attributes) |
| Has methods (code that works on the data) | No: data only | Yes |
| Can hide its data (private attributes, encapsulation) | No | Yes |
| Can be inherited from | No | Yes |
| Many copies can be made | Yes (many records) | Yes (many objects) |
Lists
A list is an ordered collection that can grow and shrink while the program runs (a dynamic structure), and, in many languages, can hold items of different types.
shopping = ["milk", "eggs"]
shopping.append("bread") # add to the end
shopping.insert(0, "tea") # add at a position
shopping.remove("eggs") # remove an item
print(shopping) # ['tea', 'milk', 'bread']
print(len(shopping)) # 3
- Mutable: items can be changed, added or removed.
- Flexible, so you don't need to know the size in advance.
- Slightly more overhead than a fixed array.
Tuples
A tuple is an ordered collection that can't be changed once created (immutable).
point = (3, 4)
print(point[0]) # 3
# point[0] = 5 # error: a tuple can't be changed
- Immutable: the values are fixed, which makes them safe, so no part of the program can alter them by mistake.
- Used for fixed groups of values: coordinates, a date (day, month, year), an RGB colour, or returning several values from a function.
- Can be used as keys in dictionaries, since they can't change.
Comparison
| Structure | Size | Element types | Changeable? | Accessed by |
|---|---|---|---|---|
| Array | Usually fixed | Same | Yes (elements) | Index |
| List | Dynamic | Often mixed | Yes | Index |
| Tuple | Fixed | Mixed | No | Index |
| Record | Fixed set of fields | Mixed | Yes | Field name |
Worked example
Task: choose a structure for each, with a reason.
- The average temperature for each month of one year. A 1D array of 12 reals: a fixed number of values of the same type, reached by month number.
- The colours of the pixels in an image. A 2D array: rows and columns of pixel values.
- Everything about one customer (name, age, balance, active). A record: related values of different types.
- A shopping basket that grows as the user adds items. A list: it needs to change size.
- The latitude and longitude of a place. A tuple: a fixed pair that shouldn't change.
Exam tip: state the key difference of each: arrays hold one type and are indexed, records hold different types and are accessed by field name, lists are dynamic, and tuples are immutable. Give a reason for your choice, linked to the data.
Check yourself
What is the difference between an array and a record?
An array holds elements of the same data type, accessed by index. A record holds related fields that can be of different types, accessed by field name.
What is the difference between a list and a tuple?
A list can be changed, with items added or removed. A tuple is immutable: it can't be changed after it has been created.
How many indexes does an element of a 2D array need?
Two: the row and the column.
How would you visit every element of a 2D array?
With nested loops: the outer loop goes through the rows and the inner loop goes through the columns.