Skip to content
Tutorials Center
My learning

Topics

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.

Python
print(["a", "b", "c", "b"].index("b"))   # 1

Try it

Python Finding positions

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.

Python All matches and safe lookups

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

Python
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 with start to get every position.
  • Missing values raise. Test with value in items first, or catch ValueError. Be aware that in followed by index() scans twice.
  • Slice-like arguments. start and end are 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.0 matches 4 and True matches 1.
  • 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 use enumerate() 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 similar find() sibling that returns -1; range.index() also exists.