Exercise 1: Cells, indices and bounds: reading a one-dimensional array
A one-dimensional array, a list in Python, stores several values under one name. Each value sits in a cell, and a cell is reached by its index, written in square brackets: data[0] is the first cell. The bounds of an array are its first and last valid indices.
data = [52, 47, 61, 49, 55, 58, 50] # line 1- a) How many elements does data hold? What are its first and last valid indices?
- b) Give the values of data[0], data[3] and data[len(data) - 1].
- c) Which whole numbers i make data[i] a valid cell? What happens when the program runs print(data[7])?
- d) After i = 2, give the values of data[i + 3], data[2 * i] and data[i] + data[i + 1].
- e) Python also accepts print(data[-1]). What does it print? In Java, an array with the same values is declared int[] data = {52, 47, 61, 49, 55, 58, 50}. What does data[-1] do there?
Show the solution
Answers
- a) 7 elements; first index 0, last index 6
- b) data[0] = 52, data[3] = 49, data[len(data) - 1] = 50
- c) The indices 0 to 6, {i ∈ ℤ | 0 ≤ i ≤ 6}; print(data[7]) stops the program with an IndexError
- d) 58, 55 and 110
- e) 50 in Python; in Java the program stops with an ArrayIndexOutOfBoundsException
Number the cells from 0 before reading anything: the drawing below shows data with its indices under the cells.
len(data) counts the elements: 7.
The first index is 0, so the last one is len(data) - 1 = 6: seven cells, numbered 0 to 6.
data[0] = 52, the first cell.
data[3] = 49: index 3 is the fourth cell, after the indices 0, 1 and 2.
data[len(data) - 1] = data[6] = 50. This expression gives the last element of an array of any length.
Pitfall: reading data[3] as the third element, 61. Index and position differ by one: the element in position k has the index k - 1.
The valid indices are the whole numbers from 0 to 6, {i ∈ ℤ | 0 ≤ i ≤ 6}: they are the bounds of data.
print(data[7]) asks for an eighth cell, which does not exist. Python stops the program with IndexError: list index out of range, and that line prints nothing.
Pitfall: taking len(data), here 7, for the last index. len counts the cells; the last index is one less.
The index is computed first, then the cell is read.
data[i + 3] = data[5] = 58.
data[2 * i] = data[4] = 55.
data[i] + data[i + 1] = data[2] + data[3] = 61 + 49 = 110: two cells are read, then added. data[i + 1] is the cell after data[i], not data[i] plus 1.
In Python, a negative index counts from the end: data[-1] is the last cell, 50, and data[-7] is the first, 52.
In Java, an index below 0 is outside the bounds: data[-1] stops the program with an ArrayIndexOutOfBoundsException.
Pitfall: a negative index produced by a mistake, such as i - 1 with i = 0, gives no error in Python: it reads the last cell without a word. Apart from one bug traced in exercise 10, the rest of this set uses indices from 0 to len - 1 only.