The index() method returns the index of a specified item in the list. If there are multiple matching items, it returns the index of the first occurrence.
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 indexing in Python starts from 0.
index() Syntax
The syntax of index() is:
result = my_list.index(item, start, end)
Arguments
index() can take a maximum of three arguments (two optional):
item- Item to be searched.start- Start search from this index. If omitted, search starts from the first item.end- Search up to this index (exclusive). If omitted, search runs through end of the list.
Basically, start and end arguments are interpreted as in slicing and used to limit the search to that particular sublist.
Return Value
index() returns the index of a specified item in the list.
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 List
models = ['Claude', 'ChatGPT', 'Gemini', 'ChatGPT']
index = models.index('Kimi')
print(index)
Output
ValueError: 'Kimi' is not in list
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 (exclusive)
index = models.index('ChatGPT', 2, 3)
print(index) # ValueError: 'ChatGPT' is not in list
Note: Python also supports negative indexing and you can use negative start and end indices with index().