![]() ![]() ![]() Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.).Check for it first with item in my_list (clean, readable approach), or.If the item might not be present in the list, you should either Throws if element not present in listĪ call to index results in a ValueError if the item"s not present. So if you"re considering reaching for index, take a look at these excellent Python features. Most places where I once would have used index, I now use a list comprehension or generator expression because they"re more generalizable. ![]() > g = (i for i, e in enumerate() if e = 1) 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 ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |