How to Find the Index of an Item in a Python List?


Use the index function of the list object:

a = ["zero", "one", "two", "three", "four"]
idx = a.index("two") # returns 2

# will raise ValueError if value is not in the list

The above method returns only the first matching index, to get all indexes, iterate over the list:

a = ["zero", "one", "two", "three", "four", "two"]
idx_list = [index for index in range(len(a)) if a[index] == 'two']
# idx_list will be [2, 5]

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?