Why does Python return negative list indexes?

后端 未结 4 727
攒了一身酷
攒了一身酷 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:26

    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])
    
    0 讨论(0)
  • 2020-11-28 16:29

    Because, index value starts from 0. In your case the last index value is 9, no more index value after 9. when you try print the values beyond the index value limit, it must throws an error

    0 讨论(0)
  • 2020-11-28 16:35

    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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题