How to obtain the last index of a list?

2020-05-22 00:01发布

Suppose I've the following list:

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

How do I obtain the last index, which in this case would be 3, of that list?

6条回答
Bombasti
2楼-- · 2020-05-22 00:34

You can use the list length. The last index will be the length of the list minus one.

len(list1)-1 == 3
查看更多
再贱就再见
3楼-- · 2020-05-22 00:35

Did you mean len(list1)-1?

If you're searching for other method, you can try list1.index(list1[-1]), but I don't recommend this one. You will have to be sure, that the list contains NO duplicates.

查看更多
对你真心纯属浪费
4楼-- · 2020-05-22 00:37

I guess you want

last_index = len(list1) - 1 

which would store 3 in last_index.

查看更多
趁早两清
5楼-- · 2020-05-22 00:46

the best and fast way to obtain last index of a list is using -1 for number of index , for example:

my_list = [0, 1, 'test', 2, 'hi']
print(my_list[-1])

out put is : 'hi'. index -1 in show you last index or first index of the end.

查看更多
太酷不给撩
6楼-- · 2020-05-22 00:53

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
查看更多
来,给爷笑一个
7楼-- · 2020-05-22 01:00
a = ['1', '2', '3', '4']
print len(a) - 1
3
查看更多
登录 后发表回答