Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index 1?
Given a list ["foo", "bar", "baz"] and an item in the list "bar" ,
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
See the documentation for the built-in
.index()method of the list:Caveats
Linear time-complexity in list length
An
indexcall checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code.This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the
startandendparameters can be used to narrow the search.For example:
The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million.
Only the index of the first match is returned
A call to
indexsearches through the list in order until it finds a match, and stops there. If there could be more than one occurrence of the value, and all indices are needed,indexcannot solve the problem:Instead, use a list comprehension or generator expression to do the search, with
enumerateto get indices:The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable.
Raises an exception if there is no match
As noted in the documentation above, using
.indexwill raise an exception if the searched-for value is not in the list:If this is a concern, either explicitly check first using
item in my_list, or handle the exception withtry/exceptas appropriate.The explicit check is simple and readable, but it must iterate the list a second time. See What is the EAFP principle in Python? for more guidance on this choice.