Why does Python return negative list indexes?

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

提交回复
热议问题