If any element which is not present is searched, then it returns the ValueError. The method index() returns the lowest index in the list that item appears.
Python list index() is an inbuilt function that searches an element in the list and returns its index. The list index() method returns the index of the element in the list.
The syntax for the index() method is the following.
list.index(element)
The element parameter is required and is searched for in the list.
The index() method returns the index of the given element in the list.
GoT = ['Daenerys', 'Jon', 'Tyrion']
elementIndex = GoT.index('Jon')
print(elementIndex)
The index() method returns an index, and in the above example, it returns Jon’s index, which is 1.
Output
1
alphabets = ['k', 'r', 'u', 'n', 'a', 'l']
index = alphabets.index('k')
print('The index of e:', index)
index = alphabets.index('a', 3, 5)
print('The index of i:', index)
Output
The index of e: 0
The index of i: 4
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
Originally published by Krunal at Appdividend
#python #python list index #valueerror