Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the last index of a 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?

like image 512
Sayuj Avatar asked Oct 25 '11 13:10

Sayuj


People also ask

How do you find the last index of a list?

pop() To demonstrate accessing the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.

How do I get the last index in Python?

To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last. The list[-1] is the most preferable, shortest, and Pythonic way to get the last element.

What is the index of the last element?

The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].

How do I get the last second index of a list?

As we want second to last element in list, use -2 as index.


2 Answers

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 
like image 169
Austin Marshall Avatar answered Oct 14 '22 08:10

Austin Marshall


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.

like image 45
Ali Akhtari Avatar answered Oct 14 '22 08:10

Ali Akhtari