The way tuple index() method works is similar to how list index() method works.
The index() method returns the index of a specified item in the tuple. If there are multiple matching items, it returns the index of the first item.
Here's a quick example:
models = ('Claude', 'ChatGPT', 'Gemini', 'ChatGPT')
index = models.index('Gemini')
print(index) # Output: 2
index = models.index('ChatGPT')
print(index) # Output: 1
It is important to note that index() returns the index, not the position. These are two different things as tuple indexing starts at 0.
index() Syntax
The syntax of index() is:
result = my_tuple.index(item, start, end)
Arguments
index() can take a maximum of three arguments (two optional):
item- Item to search for.start- Start search from this index. If omitted, search starts from the first item.end- Search the item up to this index. If omitted, search ends at the last item.
Basically, start and end arguments are interpreted as in slicing and are used to limit the search to that particular subtuple.
Return Value
index() returns the index of a specified item in the tuple.
If there are multiple matching items, it returns the index of the first item. If the item is not found, a ValueError exception is raised.
Example: Index of Item Not Found in Tuple
models = ('Claude', 'ChatGPT', 'Gemini', 'ChatGPT')
index = models.index('Kimi')
print(index)
Output
ValueError: tuple.index(x): x not in tuple
Example: index() with Start and End
models = ('Claude', 'ChatGPT', 'Gemini', 'ChatGPT')
# Search 'ChatGPT' from start to end
index = models.index('ChatGPT')
print(index) # Output: 1
# Search 'ChatGPT' from index 2 to end
index = models.index('ChatGPT', 2)
print(index) # Output: 3
# Search 'ChatGPT' from index 2 to index 3
index = models.index('ChatGPT', 2, 3)
print(index) # ValueError: tuple.index(x): x not in tuple
Note: Python also supports negative indexing and you can use negative start and end indices with index().