Python list index() method returns the index of the specified element in the list.
Syntax
list.index(element,start,end)
Parameters
- element(required): It is the item you are searching for in the list.
- start(optional): It starts searching from this index.
- end(optional): It is the position where the search ends.
Return value
This method returns the index of the given element in the list.
Example 1: How to Use list index() method
GoT = ['Daenerys', 'Jon', 'Tyrion']
elementIndex = GoT.index('Jon')
print(elementIndex)
Output
1
Example 2: Using Start and End Parameters
alphabets = ['k', 'r', 'u', 'n', 'a', 'l']
index = alphabets.index('k')
print('The index of k:', index)
index = alphabets.index('a', 3, 5)
print('The index of a:', index)
Output
The index of k: 0
The index of a: 4
Example 3: ValueError: ” is not in list
If we find an index of an element not present in the list, it will return a ValueError. Let us see the following code.
GoT = ['Daenerys', 'Jon', 'Tyrion']
elementIndex = GoT.index('Arya')
print(elementIndex)
Output
Traceback (most recent call last):
File "app.py", line 2, in <module>
elementIndex = GoT.index('Arya')
ValueError: 'Arya' is not in list
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.