4.5.6 The range function and fencepost errors

Python's multi-element objects (lists and arrays as far as the course is concerned) are all zero-offset: the first element is indexed as [0]. This is also true of C, but not true of Pascal. The first element of a Pascal array can be an arbitrary index, determined on the array's declaration. Common choices are [0] and [1].

Python's range function which allows the emulation of for loops in other languages (i.e. allows you to step through a code block, incrementing some counter by a constant index) is an example of the ``fencepost errors'' novice programmers often encounter[#!fencepost!#]

In order to generate a list that goes from 0 to n inclusive one uses range(0, n + 1) (the first argument is optional; code0 is the default). This returns a list with n + 1 elements. In the handbook student's are told: ``this may seem strange but there are reasons''. In fact problems with the range function itself were surprisingly rare (see Figure 3.9)

A more common error involved arrays. An array can be created using the zeros function which takes (at least) on argument: the number of elements in the array. For example, to create an initialised, ten-element array of integers one might do xx = zeros(10), where xx is the array. It was then common for students to get confused by fencepost errors and try and step through the elements of the array using a for loop as follows:

    >>> xx = zeros(10)
    >>> for i in range(0, 11):
    ...     print xx[i],      # (the trailing comma suppresses the new line
    ...                       # automatically included by print)
    0 0 0 0 0 0 0 0 0 0
    Traceback (most recent call last):
      File "<stdin>", line 2, in ?
    IndexError: index out of bounds

Students appeared to be confusing the fact that the last number returned by range(11) is 10 and the index of the last element of xx, which is 9. It is then that the most able students spotted the reason range works like it does; the argument given to the zeros function is almost always the same as the argument given to the range function. Demonstrators should be aware that, if they see different arguments for zeros and range, the student is probably confused. Of course in this case the error message is very descriptive.