List Methods
index()
Return the zero-based index of the first occurrence of a value.
list.index(value, start=0, stop=len(list))
list.index() searches for value and returns the zero-based index of the first match.
Optional start and stop arguments limit the search to a slice of the list. Raises ValueError if not found.
Parameters
| Name | Description |
|---|---|
| value | The value to locate. |
| start | Optional start index for the search slice (defaults to 0). |
| stop | Optional stop index for the search slice (defaults to length of list). |
Returns
The integer index of the first matching item.
Try it
Run it and change it
letters = ["p", "y", "t", "h", "o", "n"]
pos = letters.index("t")
print(f"'t' is at index: {pos}")Worth knowing
- Handling ValueErrors: If the element is not found, Python raises
ValueError. Check withif item in my_list:or wrap in atry...except ValueErrorblock.