Python 3 reference · List Methods
Python List index() Method
Return the position of the first item equal to a value. Raises ValueError if the value isn't in the list.
Python 3 Since 3.0
Syntax
list.index(value, start=0, stop=len(list))
Parameters
| Parameter | Description |
|---|---|
value |
The value to find. |
start, stop optional |
Only search this slice. |
Return value
An int.
Examples
colors = ["red", "green", "blue", "green"]
print(colors.index("green"), colors.index("green", 2))
Output
1 3
items = ["a", "b"]
print(items.index("b") if "b" in items else -1)
try:
items.index("z")
except ValueError:
print("not in list")
Output
1 not in list
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
list.count()· Return how many times a value appears in the list, comparing each item with ==. Returns 0 if it never appears.str.find()· Return the lowest index where a substring is found, or -1 if it isn't. Optional start and end limit the search.- Python Lists · tutorial