## Finding the index of an item given a list containing it in Python

Tags: python list
Question!

For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python?

By : Eugene M

And now, for something completely different, checking for the existence of the item before getting the index. The nice thing about this approach is the function always returns a list of indices -- even if it is an empty list. It works with strings as well.

``````def indices(l, val):
"""always returns a list containing the indices of val in l
"""
retval = []
last = 0
while val in l[last:]:
i = l[last:].index(val)
retval.append(last + i)
last += i + 1
return retval

l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')
``````

When pasted into an interactive python window:

``````Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
>>> def indices(l, val):
...     """always returns a list containing the indices of val in l
...     """
...     retval = []
...     last = 0
...     while val in l[last:]:
...             i = l[last:].index(val)
...             retval.append(last + i)
...             last += i + 1
...     return retval
...
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>>
``````

Problem will arrise if the element is not in the list. You can use this function, it handles the issue:

``````# if element is found it returns index of element else returns -1

def find_element_in_list(element, list_element):
try:
index_element = list_element.index(element)
return index_element
except ValueError:
return None
``````
By : tanzil

If you want all indexes, then you can use numpy:

``````import numpy as np

array = [1,2,1,3,4,5,1]
item = 1
np_array = np.array(array)
item_index = np.where(np_array==item)
print item_index
# Out: (array([0, 2, 6], dtype=int64),)
``````