How to obtain the last index of a list?

前端 未结 7 1115
野的像风
野的像风 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:36

    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.

    0 讨论(0)
  • 2021-02-01 16:36

    all above answers is correct but however

    a = [];
    len(list1) - 1 # where 0 - 1 = -1
    

    to be more precisely

    a = [];
    index = len(a) - 1 if a else None;
    
    if index == None : raise Exception("Empty Array")
    

    since arrays is starting with 0

    0 讨论(0)
  • 2021-02-01 16:38

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

    len(list1)-1 == 3
    
    0 讨论(0)
  • 2021-02-01 16:42
    a = ['1', '2', '3', '4']
    print len(a) - 1
    3
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-01 16:47

    I guess you want

    last_index = len(list1) - 1 
    

    which would store 3 in last_index.

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