How to obtain the last index of a list?

前端 未结 7 1138
野的像风
野的像风 2021-02-01 16:16

Suppose I\'ve the following list:

list1 = [1, 2, 33, 51]
                    ^
                    |
indices  0  1   2   3

How do I obtain the

7条回答
  •  臣服心动
    2021-02-01 16:43

    len(list1)-1 is definitely the way to go, but if you absolutely need a list that has a function that returns the last index, you could create a class that inherits from list.

    class MyList(list):
        def last_index(self):
            return len(self)-1
    
    
    >>> l=MyList([1, 2, 33, 51])
    >>> l.last_index()
    3
    

提交回复
热议问题