Why does Python return negative list indexes?
If I have this list with 10 elements:
>>> l = [1,2,3,4,5,6,7,8,9,0]
Why will l[10] return an IndexError, but l[-1] returns 0?
>>> l[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[0]
1
>>> l[-1]
0
>>> l[-2]
9
What I want to do is throw an error if there are no previous elements in the list.
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])
It's because l[-1]
is equal to l[len(l)-1]
,
similarly l[-2]
is equal to l[len(l)-2]
>>> lis=[1,2,3,4,5]
>>> lis[-1],lis[-2],lis[-3]
(5, 4, 3)
>>> lis[len(lis)-1],lis[len(lis)-2],lis[len(lis)-3]
(5, 4, 3)
Q: Why will l[10]
return an IndexError
, but l[-1]
returns 0
?
A: Because index values in Python (as in many other languages) are zero-based. That means the first item is stored at index 0
.
Your list
l = [1,2,3,4,5,6,7,8,9,0]
has 10 items. Since the index starts at 0
, the last item will be at index 9
. When you try to access your list at index 10
, Python rightly throws an IndexError
exception to tell you that this is not a valid index value and is out of bounds.
Python also uses the convention of negative index values to access items from the "end" of a list or sequence. Index value -1
indicates the last item in the list, -2
the next-to-last etc. Since the last item in your list is 0
, this is what l[-1]
returns.
@Lattyware's answer already shows you how to generate/throw an exception, I hope this answers your initial question.