Python List type provides the index()
method which is used to return the index numbers for the specified item. The index numbers start from0 and this means if the first item is provided the returned index value will be 0. The provided item can be a string, a number event an object.
List index() Method Syntax
The list.index() method has the following syntax which accepts 3 parameters.
LIST.index(ELEMENT,START,END)
- ELEMENT is the item or element which will be searched inside the LIST. The ELEMENT can be a string, number, object etc.
- START is the start index number where the search will start from. The START parameter is optional.
- END is the end index number where the search will end. The END parameter is optional.
The index() method returns the index number of the given element if it exists in the list. IF the given element does not exist in the list the ValueError
exception is raised.
Find Index of The Item
In the following example, we will create a list named cities
and put some city names inside it as elements. Then we will use the index()
method in order to find the index number of the “London”.
cities = ["Ankara","Istanbul","London","Berlin"]
i = cities.index("London")
print("London's index number is ",i)
As the “London” is the 3rd element and index numbers start from 0 the index number of the “London” is 2.
2
“ValueError: is not in list”
If the specified element does not exist in the list the “ValueError: is not in list” exception is raised. In the following example, we will search the item “Paris” in the list named cities but as it does not exist it will raise the ValueError exception.
cities = ["Ankara","Istanbul","London","Berlin"]
i = cities.index("Paris")
print("Paris's index number is ",i)
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 'Paris' is not in list
Specify Start For Index
By default, the index search operation is done in the whole list for all elements. But we can restrict this search and specify the start index number where the search will be started. In the following example, we start the search from index number 1.
cities = ["Ankara","Istanbul","London","Berlin"]
i = cities.index("Lodon",1)
print("London's index number is ",i)
Specify Start and End For Index
Another way to limit element index number search is by specifying the start and end numbers for the search. This means the specified element will be searched between specified index numbers. In the following example, we search “London” between index numbers 1 and 3.
cities = ["Ankara","Istanbul","London","Berlin"]
i = cities.index("Lodon",1,3)
print("London's index number is ",i)