Given a list [\"foo\", \"bar\", \"baz\"]
and an item in the list \"bar\"
, how do I get its index (1
) in Python?
As indicated by @TerryA, many answers discuss how to find one index.
more_itertools is a third-party library with tools to locate multiple indices within an iterable.
Given
import more_itertools as mit
iterable = ["foo", "bar", "baz", "ham", "foo", "bar", "baz"]
Code
Find indices of multiple observations:
list(mit.locate(iterable, lambda x: x == "bar"))
# [1, 5]
Test multiple items:
list(mit.locate(iterable, lambda x: x in {"bar", "ham"}))
# [1, 3, 5]
See also more options with more_itertools.locate. Install via > pip install more_itertools.