40

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?

nbro
  • 13,796
  • 25
  • 99
  • 185
Sayuj
  • 7,246
  • 11
  • 57
  • 75
  • Does this answer your question? [Getting the last element of a list](https://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list) – Gino Mempin Apr 13 '20 at 23:58

8 Answers8

41

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
Austin Marshall
  • 2,863
  • 14
  • 14
31

The best and fast way to obtain the content of the 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])

Output is: 'hi'.

Index -1 shows you the last index or first index of the end.

But if you want to get only the last index, you can obtain it with this function:

def last_index(input_list:list) -> int:
    return len(input_list) - 1

In this case, the input is the list, and the output will be an integer which is the last index number.

Ali Akhtari
  • 1,164
  • 2
  • 16
  • 40
15

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.

nbro
  • 13,796
  • 25
  • 99
  • 185
Gandi
  • 3,402
  • 2
  • 20
  • 30
  • Ohhh man so wise, I was going with `len(list1)-1` at first, then thought about a more Pythonic way, imagined that one, but then came here and thanks to your answer you've just saved me of a serious headache –  Aug 23 '18 at 17:30
13

I guess you want

last_index = len(list1) - 1 

which would store 3 in last_index.

nbro
  • 13,796
  • 25
  • 99
  • 185
UncleZeiv
  • 17,722
  • 6
  • 48
  • 77
1

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

Mark Anthony Libres
  • 594
  • 1
  • 5
  • 12
1

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

len(list1)-1 == 3
nbro
  • 13,796
  • 25
  • 99
  • 185
Diego Navarro
  • 8,636
  • 3
  • 25
  • 33
0
a = ['1', '2', '3', '4']
print len(a) - 1
3
Haresh Shyara
  • 1,578
  • 9
  • 13
-3
list1[-1]

will return the last index of your list.

If you use minus before the array index it will start counting downwards from the end. list1[-2] would return the second to last index etc.

Important to mention that -0 just returns the "first" (0th) index of the list because -0 and 0 are the same number,

Osi
  • 307
  • 1
  • 12