For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?
Join them; it only takes a minute:
|
|
Reference: Data Structures > More on Lists |
|||||||||||||||||||||
|
|
One thing that is really helpful in learning Python is to use the interactive help function:
which will often lead you to the method you are looking for. |
|||||||||
|
|
I'm honestly surprised no one has mentioned
This can be more useful than index if there are duplicates in the list, because index() only returns the first occurrence, while enumerate returns all occurrences. As a list comprehension:
Here's also another small solution with
This is more efficient for larger lists than using
|
|||||||||||||
|
|
|
|||||
|
|
To get all indexes:
|
|||
|
|
|
|||||||||||||||||
|
|
A problem will arise if the element is not in the list. This function handles the issue:
|
|||||||||||||||||||||
|
|
You have to set a condition to check if the element you're searching is in the list
|
|||||
|
|
All of the proposed functions here reproduce inherent language behavior but obscure what's going on.
Why write a function with exception handling if the language provides the methods to do what you want itself? |
|||||
|
|
If you want all indexes, then you can use numpy:
It is clear, readable solution. |
|||||
|
|
Simply you can go with
|
|||
|
|
|
all indexes with zip function
|
|||
|
|
|
Another option
|
|||
|
|
|
A variant on the answer from FMc and user7177 will give a dict that can return all indices for any entry:
You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called. |
|||
|
|
|
This solution is not as powerful as others, but if you're a beginner and only know about
|
|||
|
|
|
And now, for something completely different, checking for the existence of the item before getting the index. The nice thing about this approach is the function always returns a list of indices -- even if it is an empty list. It works with strings as well.
When pasted into an interactive python window:
|
||||
|
|
This accounts for if the string is not in the list too, if it isn't in the list then location = -1 |
|||
|
|
protected by Styvane Apr 15 '16 at 16:14
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?