3.2.6 - One-dimensional arrays (Python)
An indexed collection stores related values together so that one algorithm can process them. This lesson uses Python lists as the array equivalent for storing, traversing and updating a series of measurements.
Indexed collections
A data structure organises data so that a program can store and access it for a particular task.
One-dimensional array
An indexed collection of elements arranged in one sequence. One index identifies an element.
Daily temperatures, pupil scores and stock quantities are useful examples. An array lets the program process every value with one loop instead of using separate variables such as score1, score2 and score3. In Python we use a list as an equivalent indexed collection. Lists have extra capabilities and can mix types, but these examples store values with one common meaning and type.
temperatures = [17, 20, 18, 22]
print(temperatures[0])
print(len(temperatures))
The first output is 17 and the second is 4. Python indexes begin at zero, so valid indexes here are 0–3. Index 3 contains 22; index 4 is outside the list. Length counts elements, while an index identifies a position. AQA supplied arrays are also zero-based unless the question states otherwise.
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Temperature | 17 | 20 | 18 | 22 |
Square brackets create a list and also select an element. Read the context: the comma-separated values define the collection; the single index after its name accesses one value.
Traversing and changing an array
Traversal visits the elements in turn so that the same processing can be applied to each one.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account