liveBook · Manning

IndexError

As explained in The Quick Python Book, Fourth Edition

IndexError is a Python exception raised when a sequence or indexed access is requested outside its valid range.

IndexError signals that an indexed access has gone beyond the available items. For example, `alist = [1, 2, 3]` followed by `alist[7]` raises `IndexError: list index out of range`. If nothing catches it, Python reports the exception at the top level. section 14.2.2

Code can raise the exception explicitly with `raise IndexError(...)`; a message argument can explain what went wrong. IndexError is a subclass of LookupError, which is a subclass of Exception. Put an `except IndexError` clause before an `except LookupError` clause if the two need different handling: the broader clause would otherwise catch both. section 14.2.2 section 14.2.7

class LineReader:
    def __init__(self, filename):
        self.fileobject = open(filename, 'r')        #1
    def __getitem__(self, index):
        line = self.fileobject.readline()            #2
        if line == "":                               #3
            self.fileobject.close()                  #4
            raise IndexError                         #5
            
        else:
            return line.split("::")[:2]              #6
 
for name, age in LineReader("filename"):
    . . . do whatever . . .

The `LineReader` example defines `__getitem__` to return successive file lines. At end of file, it closes the file and raises IndexError, ending the enclosing `for` loop. section 17.7 section 17.7.1

That file reader is illustrative, not usually the simplest way to iterate over a file; `for line in fileobject` is generally sufficient. Likewise, do not add an IndexError handler merely because a requested count exceeds a list’s length: first check whether the code can actually raise one. section 17.7.1 section 14.4.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through automatic and explicit raising, handler inheritance, and loop termination; notes that the file-reader implementation is illustrative.
Examples
Uses an out-of-range three-item list access and a file reader that raises IndexError at end of file.
What it assumes
Assumes familiarity with list indexing and functions; introduces exception inheritance without requiring prior object-oriented programming.
What you can do after
Build it from scratch in a __getitem__-based reader, or distinguish necessary IndexError handling from a catch that cannot run.
How it connects
Connects IndexError to LookupError, exception handlers, __getitem__, sequence iteration, and file reading.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.