Tuple Methods
index()
Find the zero-based index of the first occurrence of an item.
tuple.index(value, start=0, stop=len(tuple))
tuple.index() searches for value within the optional start and stop slice boundaries and returns the index of its first occurrence.
If the value is not found, it raises a ValueError exception.
Parameters
| Name | Description |
|---|---|
| value | The item to find. |
| start | Optional start index for the search slice (defaults to 0). |
| stop | Optional stop index for the search slice (defaults to the length of the tuple). |
Returns
The integer index of the first matching element.
Try it
Run it and change it
fruits = ("apple", "banana", "cherry", "banana", "date")
first_banana = fruits.index("banana")
second_banana = fruits.index("banana", first_banana + 1)
print(first_banana, second_banana)Worth knowing
- Missing item handling: Raises
ValueErrorifvaluedoes not exist in the searched slice. Useif value in tuple:before callingindex()if unsure. - Sub-slice searching: The
startandstopparameters allow you to search within specific ranges without creating a sliced copy.