1.4.2 - Arrays, records, lists and tuples
A booking program needs to store seat availability, details of each booking, and an ordered collection of bookings. These are different jobs. You will choose a suitable structure, interpret arrays with up to three indices, and follow the actual steps needed to create, traverse, insert and remove data.
Choose a structure from the data's job
A data structure organises values so that a program can access and change them in useful ways. Its contract includes what an element contains, how it is located, and which changes are permitted.
Array
An array is an indexed collection with a defined size whose elements have the same declared type. Changing an existing element does not resize the array.
A timetable with 30 integer occupancy counts has a known number of positions, and each count has the same meaning. Reserving 30 slots does not mean that all 30 currently contain meaningful bookings: an application can maintain a separate count of active entries.
A record groups named fields describing one entity. A booking might have an identifier string, an integer seat number and a Boolean payment flag. The fields can have different types, and their names explain their roles. An array of booking records still has one element type: each element is a booking record, even though fields within a record differ.
A list is an ordered collection whose length can grow or shrink. It is useful for a changing set of waiting passengers. In the usual OCR comparison, arrays have a fixed size and homogeneous elements, whereas lists can vary in size and may hold different types. An individual language or library may impose further restrictions; always read the given declaration or contract. A tuple is an ordered collection whose positions cannot be reassigned after it is created. It suits a fixed grouping such as a pair of coordinates.
Do not confuse the abstract structure with the spelling used by a language. Python's built-in list is a resizable container: using one to model an array does not make it a fixed-size array. Python has no built-in OCR-style record declaration; a dictionary with named keys or an object can represent a record. These representations will be identified explicitly below.
Choose from the data's meaning: an array groups indexed same-type elements; a record groups named fields of one entity. Python's container spelling does not decide which role it is modelling.
Locate values with one, two or three indices
An array's dimensions describe how many indices locate one element, not the number of values stored. OCR's printed pseudocode uses zero-based indices and the keyword array. A size is a count: array delay[4] provides positions 0 to 3, not 0 to 4.
array delay[4]
delay[0] = 5
delay[1] = 0
delay[2] = 8
delay[3] = 2
print(delay[2])
This prints 8. An out-of-range index such as 4 does not create an extra array slot.
A two-dimensional array might use [row,column] for a seating grid. The following values define array seats[2,3] completely; 1 means occupied and 0 means free.
| Row index | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 |
seats[1,2] is 1. There are six elements, with row indices 0..1 and column indices 0..2. Traversal means visiting the required elements in a stated order. This row-by-row traversal prints 1, 0, 1, 0, 0, 1, each on a separate line:
for row = 0 to 1
for column = 0 to 2
print(seats[row,column])
next column
next row
A three-dimensional array adds a third index. Suppose occupancy[day,row,column] has dimensions [2,2,3]. It stores two days, each with two rows and three seats, so it has elements. Day 0 is the seats table above; day 1 has rows [0,1,0] and [1,1,0]. Thus occupancy[1,0,1] = 1 and occupancy[0,1,0] = 0. Choose the index meanings before using a value: swapping day and row may address a different valid element and give a silent logical error.
Python nested lists are a convenient representation, using successive brackets rather than OCR's comma notation. This sandbox is ungraded: predict, then run and modify the data.
Explore a three-dimensional array
{"exercise_id":"h446-arrays-occupancy-explore","task_version":"1","runtime_profile":"python-console-v1","original_filename":"occupancy.py","file_mode":"fresh","code":"occupancy = [[[1, 0, 1], [0, 0, 1]],\n [[0, 1, 0], [1, 1, 0]]]\ntotal = 0\nfor day in occupancy:\n for row in day:\n for seat in row:\n total += seat\nprint(occupancy[1][0][1])\nprint(total)\n","instructions":"Predict both printed values before Run. Change the middle value of day 1, row 0 from 1 to 0, then predict and rerun. Restore it and change that value to 3: observe that Python permits this even though it violates the declared 0/1 occupancy meaning. Run explores behaviour; it does not submit or award marks."}
The output is 1 then 6. Each nested loop changes one level; the innermost variable is one seat value. These are explicitly supplied rectangular nested lists. Python does not enforce that every row has the same length or every entry has the same type; an array model must maintain those requirements itself.
Changing the selected cell to 0 gives 0 then 5; changing it to 3 gives 3 then 8. The latter executes, but it is no longer a valid occupied/free flag. Successful execution does not establish that the data meet the model's contract.
Create and traverse records with named fields
A record keeps the fields of one entity together, so changing one field does not mean changing the entity's position in a collection. Use field names consistently: the integer seat is a seat number, while paid records a true/false state.
Record
A record groups named fields about one entity. Field roles and types are defined by the record's layout; updating a field retains the entity.
Here dictionaries represent booking records, and a Python list stores the records. Braces create a dictionary; square brackets create the surrounding list. This is a representation choice, not an OCR record syntax requirement. Use this ungraded sandbox to distinguish field changes from whole-entry changes.
Update and traverse booking records
{"exercise_id":"h446-records-bookings-explore","task_version":"1","runtime_profile":"python-console-v1","original_filename":"bookings.py","file_mode":"fresh","code":"bookings = [\n {"name": "Nia", "seat": 12, "paid": False},\n {"name": "Omar", "seat": 7, "paid": True}\n]\nbookings[0]["paid"] = True\nbookings.append({"name": "Pia", "seat": 3, "paid": False})\nfor booking in bookings:\n if not booking["paid"]:\n print(booking["name"])\n","instructions":"Predict which names print before Run. Change the update to set Nia's paid field to False and predict again. Restore the original update, insert del bookings[1] before the loop, and compare the names and list length: deleting Omar is a whole-entry change, whereas Nia's update is a field change. These experiments are ungraded."}
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account