pysnippets.lists.index_of_all
Find every index of a value
index_of_all(items: Iterable[T], value: T) -> list[int]Return every index at whichvalueoccurs initems.find_index_of_all(items: Iterable[T], predicate: Callable[[T], object]) -> list[int]Return every index whose item passespredicate.
Return all positions of a value, or of items matching a predicate.
list.index() finds the first match only, and raises if there is none. These return every match, and an empty list when there’s none.
index_of_all.py✓ ruff · mypy --strict
from collections.abc import Callable, Iterable
from typing import TypeVar
T = TypeVar("T")
def index_of_all(items: Iterable[T], value: T) -> list[int]:
"""Return every index at which ``value`` occurs in ``items``."""
return [i for i, item in enumerate(items) if item == value]
def find_index_of_all(
items: Iterable[T], predicate: Callable[[T], object]
) -> list[int]:
"""Return every index whose item passes ``predicate``."""
return [i for i, item in enumerate(items) if predicate(item)]- enumerate pairs each item with its index
examples✓ 4 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> index_of_all([1, 2, 1, 4, 5, 1], 1)[0, 2, 5]passed on Python 3.11 to 3.14: >>> index_of_all([1, 2, 3, 4], 6)[]passed on Python 3.11 to 3.14: >>> find_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1)[0, 2]passed on Python 3.11 to 3.14: >>> find_index_of_all("Hello World", str.isupper)[0, 6]Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
enumeratepairs each item with its index.index_of_allcompares with==;find_index_of_alltakes any test.- Both work on any iterable, including strings and generators.
Complexity: O(n) time, O(k) space for k matches
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.lists.index_of_all import index_of_all, find_index_of_allNo dependencies: copy index_of_all.py into your project, or clone the repo.Adapted from index-of-all and find-index-of-all in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Merged two snippets into one page; typed. Suggest an edit.