find_index()
Gets the index at which the first occurrence of value is found.
Implementation
Args: array: List to search. filter_by: Value to search for. Returns: Index of the matched value, otherwise -1.
Example
find_index([1, 2, 3, 4, 5], 3)
Expected output: 2
Alternative usage:
find_index([1, 2, 3, 4, 5], 6)
Expected output: -1
Source Code
def find_index(
array: List[T], filter_by: Union[Callable[[T], bool], Dict[str, Any], Any]
) -> int:
if callable(filter_by):
predicate = filter_by # type: ignore
elif isinstance(filter_by, dict):
def predicate(x): # type: ignore
return all(x.get(k) == v for k, v in filter_by.items()) # type: ignore
else:
def predicate(x):
return x == filter_by # type: ignore
for idx, item in enumerate(array):
try:
if predicate(item):
return idx
except Exception:
continue
return -1