Why does Python return negative list indexes?

In Python, negative list indices indicate items counted from the right of the list (that is, l[-n] is shorthand for l[len(l)-n]).

If you find you need negative indices to indicate an error, then you can simply check for that case and raise the exception yourself (or handle it then and there):

index = get_some_index()
if index < 0:
    raise IndexError("negative list indices are considered out of range")
do_something(l[index])

Leave a Comment