Lists in Python allows duplicate elements, this means that an object can appear more than once in a particular list.The index() method in lists returns the leftmost index of an element.

Syntax:
index(x)
copy

Where x is the element whose index we want.

ExampleEdit & Run
cities = ['Ottawa', 'Nairobi', 'Manilla', 'Delhi', 'Helsinki']

#get the index of 'Manilla'
result = cities.index('Manilla')

print(result)
copy
Output:
2 [Finished in 0.010449685156345367s]

The function only returns the leftmost index even if the elements appears more than once in the list. 

ExampleEdit & Run
cities = ['Ottawa', 'Nairobi', 'Manilla', 'Delhi', 'Helsinki', 'Manilla']

#get the index of 'Manilla'
result = cities.index('Manilla')

print(result)
copy
Output:
2 [Finished in 0.010248958133161068s]

A ValueError exception is raised if the given element does not exist in the target list. 

ExampleEdit & Run
cities = ['Ottawa', 'Nairobi', 'Manilla', 'Delhi', 'Helsinki']

cities.index('Tokyo')
copy
Output:
Traceback (most recent call last):   File "<string>", line 3, in <module> ValueError: 'Tokyo' is not in list [Finished in 0.009984890930354595s]

To avoid the ValueError exception,  we can use the in operator to check whether an element exist in the target list before we try to get its index.

ExampleEdit & Run
cities = ['Ottawa', 'Nairobi', 'Manilla', 'Delhi', 'Helsinki']

city1 = 'Delhi'
city2 = 'Tokyo'

for city in (city1, city2):
    if city in cities:
        print(cities.index(city))
    else:
        print(f'{city} not found.')
copy
Output:
3 Tokyo not found. [Finished in 0.009871627669781446s]

Get all the indices of an element 

The builtin enumerate() function returns an iterator object which contains tuples of the form (index, item). We can use the function in a loop then check after every iteration if the current object is equal to the elements whose indices we want.

The following example shows how we can achieve this using list comprehension.

ExampleEdit & Run
 mylist = [2, 1, 8, 1, 5, 4, 1, 3]
item = 1

indices = [i for (i, v) in enumerate(mylist) if v==item ]
print(indices) 
copy
Output:
[1, 3, 6] [Finished in 0.009723917115479708s]

The for loop equivalent of the above example is as shown below.

ExampleEdit & Run
 mylist = [2, 1, 8, 1, 5, 4, 1, 3]
item = 1

indices = []

for (i, v) in enumerate(mylist):
    if v == item:
        indices.append(i)

print(indices) 
copy
Output:
[1, 3, 6] [Finished in 0.009894040878862143s]