The list is a container data type that represents a collection of ordered elements in which an element can be accessed using an index.

Lists allow duplicate elements meaning that an item can appear more than once.

The index() method returns the leftmost  index of an element in the list.

mylist = ["Java", "C++", "Python", "Ruby"]

#get the index of an element
print('Python is at index, ', mylist.index('Python'))
print('Java is at index, ', mylist.index('Java'))

The syntax of the index() method is as shown below. 

lst.index(item, start = 0, end = None)
item The item whose index we want.
start Optional. The index at which the search will begin. Defaults to 0.
end Optional. The index at which the search will stop. If not given, the search goes on up to the end of the list.

The index() method returns the first/leftmost index where the input item appears in the list starting from the index 'start' and ending at the index specified by the 'end' argument if given.

A ValueError is raised if the item does not appear in the list between start and end. If start is not given, it defaults to 0 and if 'end' is not given, the search goes on up to the end of the list.

mylist = ['Python', 'Java', 'Python', 'C++']


In the above example, 'Python' appears twice in the list but only the first index is returned. Consider the following example with 'start' value given.

mylist = ['Python', 'Java', 'Python', 'C++', 'Python']

print(mylist.index('Python', 1))

In the above example, we gave 1 as the value of start meaning that the search begins at index 1. Thus the index that gets returned is the one at which 'Python'  is first encountered starting from index 1 to the end of the list.

If the item does not exist from 'start' to 'end'

If the value given to the index() method does not exist in the list from the index specified by argument 'start' to the one specified by argument 'end', a ValueError is raised.

mylist = ['Python', 'Java', 'C++']


To avoid this exception from being raised, we can check explicitly whether the element exists in the list before calling the index() method. 

mylist = ['Python', 'Java', 'C++', 'PHP']
value = 'Ruby'

if value in mylist:

In  the above example we used the if statement with a condition to check whether the target value exists in the list. We print -1 if the value does not exist in the list.

You can also use other means such as the try/except block to catch the exception when it is raised.