M&C3: Using an index lying outside the list (typically an off-by-1 error)

A common challenge students encounter relates to iterating with index values through a list within a loop. Many students recognize that a list has boundaries, but due to the off-by-one error, they write code that attempts to execute with an index equal to the length of the list.

In Python (and many other languages), indexing starts at 0. The first element in the list S is at S[0] and the last element in list S is S[len(S)-1]. Even savvy programmers can get boundary conditions on lists (and strings, arrays, etc) wrong. Tell your students to always think through boundary conditions and to not trust their intuition.

Python Example:

myData = [1, 2, 1, 2, 1]
i = 0
while i <= len(myData) :

    myData[i] = myData[i] / 2

    i = i + 1

    # when i = 5 -> "IndexError: list index out of range"

Video Length: 2:15

 

Remind students that while Python allows negative indices, this does not eliminate the problem of lying outside the correct range.   Using the negative index, the leftmost element in list myData is myData[-5]. If a student uses myData[-6] , or any smaller negative index, to retrieve a list element, the error message: “IndexError: list index out of range” is generated.