

If you expect to need indices of more matches, you should use a list comprehension, or generator expression. Only returns the index of the first match to its argumentĪ call to index searches through the list in order until it finds a match, and stops there. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999), because the former only has to search 10 entries, while the latter searches a million: > import timeit Note that if you know roughly where to find the match, you can give index a hint. In that case, you should consider a different data structure. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. Linear time-complexity in list lengthĪn index call checks every element of the list in order, until it finds a match. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

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. Raises a ValueError if there is no such item. Return zero-based index in the list of the first item whose value is equal to x. It is probably worth initially taking a look at the documentation for it: list.index(x]) It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Note that while this is perhaps the cleanest way to answer the question as asked, index is a rather weak component of the list API, and I can't remember the last time I used it in anger. Reference: Data Structures > More on Lists Caveats follow
