Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding first and last index of some value in a list in Python

Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:

verts.IndexOf(12.345) verts.LastIndexOf(12.345) 
like image 612
Joan Venge Avatar asked Feb 06 '09 22:02

Joan Venge


People also ask

How do you find the first index of a value in a list Python?

To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.

How do I find the first and last element of a list in Python?

The first element is accessed by using blank value before the first colon and the last element is accessed by specifying the len() with -1 as the input.

How do you find the index of a specific value in Python?

The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.


2 Answers

Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value).

You can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)

like image 128
SilentGhost Avatar answered Sep 23 '22 02:09

SilentGhost


If you are searching for the index of the last occurrence of myvalue in mylist:

len(mylist) - mylist[::-1].index(myvalue) - 1 
like image 44
user2669486 Avatar answered Sep 26 '22 02:09

user2669486