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?
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?
You can use the list length. The last index will be the length of the list minus one.
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.I guess you want
which would store 3 in
last_index
.the best and fast way to obtain last index of a list is using
-1
for number of index , for example:out put is :
'hi'
. index-1
in show you last index or first index of the end.len(list1)-1
is definitely the way to go, but if you absolutely need alist
that has a function that returns the last index, you could create a class that inherits fromlist
.