Why does Python return negative list indexes?

后端 未结 4 739
攒了一身酷
攒了一身酷 2020-11-28 16:03

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?

4条回答
  •  时光取名叫无心
    2020-11-28 16:45

    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.

提交回复
热议问题