Given a list [\"foo\", \"bar\", \"baz\"]
and an item in the list \"bar\"
, how do I get its index (1
) in Python?
using dictionary , where process the list first and then add the index to it
from collections import defaultdict
index_dict = defaultdict(list)
word_list = ['foo','bar','baz','bar','any', 'foo', 'much']
for word_index in range(len(word_list)) :
index_dict[word_list[word_index]].append(word_index)
word_index_to_find = 'foo'
print(index_dict[word_index_to_find])
# output : [0, 5]
Simply you can go with
a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']
res = [[x[0] for x in a].index(y) for y in b]
Since Python lists are zero-based, we can use the zip built-in function as follows:
>>> [i for i,j in zip(range(len(haystack)), haystack) if j == 'needle' ]
where "haystack" is the list in question and "needle" is the item to look for.
(Note: Here we are iterating using i to get the indexes, but if we need rather to focus on the items we can switch to j.)
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),)
It is clear, readable solution.
There is a chance that that value may not be present so to avoid this ValueError, we can check if that actually exists in the list .
list = ["foo", "bar", "baz"]
item_to_find = "foo"
if item_to_find in list:
index = list.index(item_to_find)
print("Index of the item is " + str(index))
else:
print("That word does not exist")
Finding index of item x in list L:
idx = L.index(x) if (x in L) else -1