1D Arrays
To use a single value from an array, write the array identifier followed by the element's index in square brackets. Indexing starts at zero, so for an array called shelf, shelf[0] is the first element and shelf[2] is the third.
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Element | dragon | robot | puzzle | kite |
shelf = ["dragon", "robot", "puzzle", "kite"]
position = 2
print(shelf[0])
print(shelf[position])
shelf[1] = "rocket"
print(shelf[1])
print(len(shelf))
print(shelf[len(shelf) - 1])Output:
dragon
puzzle
rocket
4
kite
The index does not have to be written out as a number. It can be a variable such as position, or a calculated expression such as i + 1. That is what allows a loop to work through an array, using its counter as the index so a different element is reached on each pass.
Assigning to an element with = replaces whatever value was already stored at that index. It does not insert an extra element or shuffle the others along, so the array keeps the same length: the contents change, but the structure stays as it was.
The function len() returns the number of elements an array holds, so len(shelf) is 4. Because counting starts at zero, the last valid index is always one less than the length, which here is len(shelf) - 1, or 3. Writing the last index as len(shelf) reaches one place too far.
Any index outside the range of the array, such as shelf[4] for this array, causes an IndexError. This is a runtime error rather than a syntax error: the code is valid and starts running, but it crashes at that line and nothing after it is carried out.
badges = ["bronze", "silver", "gold"]
print(badges[3])Output:
IndexError: list index out of range (line 2) OCR GCSE Computer Science · 1D Arrays