How to find the index or indexes of an item in a list in Python
list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError
if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
The caveat follows
The index() method of the list object is so inefficient when your list becomes way to big. It checks every element from the start until it finds the element or to the end. When you don't know roughly the place of your searching element in such a large list, you should consider another data structure to avoid this overhead.
If you do know the rough place where you could find the match, you should restrict the searching range by using start and end parameters, such as list.index(l, 100_000_000, 100_000_100).
How to return all the indexes of an item in a list
For this end, we could use a list comprehension
>>> l = ['a','b','d','e','a','f','g','a']
>>> [i for i, e in enumerate(l) if e=='a' ]
Comments
Post a Comment