Python Glossary Русский

all Python 3Exceptionsexception

IndexError

built-in exceptions

Raised when a sequence is indexed with an index that does not exist.

Syntax

raise IndexError('сообщение')

Negative indices count from the end but hit the same wall: on a three-element list, lst[-4] raises IndexError just like lst[5]. Slicing, unlike indexing, never raises — lst[5:10] on a short list quietly returns an empty list, which hides bugs that an exception would have exposed. The dictionary counterpart is KeyError; both inherit from LookupError if you want to catch them together.

Examples

lst = [1, 2, 3]
lst[5]               # IndexError
lst[-1]              # 3 — ok
try:
    print(lst[10])
except IndexError:
    print('нет такого индекса')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy