list.index()
Returns the position of the first item equal to a value. Raises ValueError when the value is not in the list.
list.index(x[, start[, end]])index(x) searches the list from the left and tells you the position of the first item equal to x. Positions start at 0.
You can limit the search to part of the list with start and end, which is handy for finding the second or third match.
Unlike str.find() for strings, there is no "not found" value such as -1. A missing value raises a ValueError, so check with in first when the value may be absent.
Parameters
| Parameter | What it is |
|---|---|
xrequired | The value to look for. Items are compared with ==. |
startoptional, default 0 | The position where the search begins. Give it by position, items.index(x, 2): start=2 raises TypeError. |
endoptional, default len(list) | The position where the search stops. This position itself is not searched. |
Return value
An integer: the position of the first match. The result is still counted from the start of the whole list, even when you give start.
Examples
1Find where an item is
planets = ["Mercury", "Venus", "Earth", "Mars"]
print(planets.index("Earth"))2
2Find the second match with start
visits = ["home", "shop", "home", "cart"]
first = visits.index("home")
second = visits.index("home", first + 1)
print(first, second)0 2
3Check before searching
menu = ["soup", "pasta", "salad"]
for dish in ["pasta", "pizza"]:
if dish in menu:
print(dish, "is number", menu.index(dish) + 1)
else:
print(dish, "is not on the menu")pasta is number 2 pizza is not on the menu
4Find all positions of a value
index() only returns the first match. To get every position, use enumerate().
scores = [7, 10, 4, 10, 9]
best = max(scores)
where = [i for i, s in enumerate(scores) if s == best]
print(where)[1, 3]
Common mistakes
Looking for a value that is missing
index() raises ValueError. Test with in, or catch the error.
colors = ["red", "blue"]
try:
print(colors.index("green"))
except ValueError:
print("ValueError: green is not in the list")ValueError: green is not in the list
Expecting -1 like str.find()
Lists have no find() method and never return -1. If you want a default, write it yourself: pos = items.index(x) if x in items else -1.
items = ["a", "b"]
x = "z"
pos = items.index(x) if x in items else -1
print(pos)-1
Questions people ask
How do I get the index of an item in a Python list?
items.index(value) gives the first position. Use enumerate() when you need every position.
How do I find the index of the largest number?
scores.index(max(scores)) gives the position of the first largest value.
Is index() slow?
It checks the items one by one, so on a very long list it takes longer. If you search the same list many times, a dictionary from value to position is faster.