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.

index(x)

Where x is the element whose index we want.

cities = ['Ottawa', 'Nairobi', 'Manilla', 'Delhi', 'Helsinki']

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

print(result)

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

cities = ['Ottawa', 'Nairobi', 'Manilla', 'Delhi', 'Helsinki', 'Manilla']

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

print(result)

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

cities = ['Ottawa', 'Nairobi', 'Manilla', 'Delhi', 'Helsinki']

cities.index('Tokyo')

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.

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.')

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.

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

indices = [i for (i, v) in enumerate(mylist) if v==item ]
print(indices) 

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

 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)