How to obtain the last index of a list?
I guess you want
last_index = len(list1) - 1
which would store 3 in last_index
.
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.
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.
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