Why does Python return negative list indices?

If I have this list with 10 items:

>>> l = [1,2,3,4,5,6,7,8,9,0]

Why does 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

I want to make a mistake if there are no previous items in the list.

+5
source share
3 answers

In Python, negative list indexes indicate the elements counted to the right of the list (i.e., it l[-n]is short for l[len(l)-n]).

If you find that you need negative indexes to indicate an error, you can simply check this case and throw an 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])
+19
source

This is because l[-1]equal l[len(l)-1], similarly l[-2]equall[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)
+2
source

Q: l[10] IndexError, l[-1] 0?

A. Python ( ) . , 0.

l = [1,2,3,4,5,6,7,8,9,0]

10 . 0, 9. 10, Python IndexError, , .

Python also uses a negative index convention to access items from the "end" of a list or sequence. The index value -1indicates the last item in the list, -2following the last, etc. Since the last item on your list 0, this is what returns l[-1].

@Lattyware's answer already shows you how to throw / throw an exception, I hope this answers your original question.

+1
source

All Articles