Python Reference ยท Lists, Tuples and Ranges
Python list.index() method
Reference for Python list.index(): find the position of the first matching item, search a range with start and end, handle ValueError and find every match.
The index() method returns the position of the first item in a list that equals the value you give it. Positions start at 0. If the value is not in the list, Python raises ValueError; unlike str.find(), there is no "return -1" version.
You can limit the search to part of the list with optional start and end arguments, which is the usual way to find the second or third occurrence.
print(["a", "b", "c", "b"].index("b")) # 1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.index(value) list.index(value, start) list.index(value, start, end)
| Name | Description |
|---|---|
value |
The object to look for; items are compared with ==. |
start |
Optional. The position where the search begins. Negative values count from the end. |
end |
Optional. The position where the search stops (exclusive). |
Return value: the index of the first match, counted from the beginning of the whole list (not from start).
Raises: ValueError if the value is not found in the searched range.
Usage notes
- Only the first match. Use a comprehension with
enumerate()or a loop withstartto get every position. - Missing values raise. Test with
value in itemsfirst, or catchValueError. Be aware thatinfollowed byindex()scans twice. - Slice-like arguments.
startandendare interpreted like slice bounds: they are clamped to the list, and negative numbers count from the end. The result is still an index into the full list. - Equality semantics.
4.0matches4andTruematches1. - Linear time. Searching is O(n). For many lookups, build a dictionary of value to position, or keep the data sorted and use
bisect. - Duplicates. If values repeat,
index()is not a reliable "identity" of an item. Store IDs or useenumerate()in your loop to keep the position you already have. - Same method elsewhere:
tuple.index()behaves identically;str.index()finds a substring and has a similarfind()sibling that returns -1;range.index()also exists.
Related
list.count(),list.insert(),list.remove(),enumerate(),str.find(),list- Lessons: Lists, List methods