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.
You can use the list length. The last index will be the length of the list minus one.
len(list1)-1 == 3
I guess you want
last_index = len(list1) - 1
which would store 3 in last_index
.
a = ['1', '2', '3', '4']
print len(a) - 1
3
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.
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
Source: Stackoverflow.com