fluttersmith/py-snippetsGitHub ↗

Find every index of a value

Return all positions of a value, or of items matching a predicate.

Lists#searchO(n) time✓ 4 examples pass on 3.11–3.14

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)]
  1. 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).

How it works

  • enumerate pairs each item with its index.
  • index_of_all compares with ==; find_index_of_all takes any test.
  • Both work on any iterable, including strings and generators.

Complexity: O(n) time, O(k) space for k matches

Importfrom 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.