fluttersmith/py-snippetsGitHub ↗

List intersection by a key

Keep the items of one list whose key also appears in another, preserving order.

Lists#setsO(n + m) time✓ 3 examples pass on 3.11–3.14

Find the users in the old list that also exist in the new one, matching case-insensitively, or by ID.

intersection_by.py✓ ruff · mypy --strict
from collections.abc import Callable, Hashable, Iterable
from typing import TypeVar

T = TypeVar("T")
K = TypeVar("K", bound=Hashable)


def intersection_by(a: Iterable[T], b: Iterable[T], key: Callable[[T], K]) -> list[T]:
    """Return the items of ``a`` whose ``key`` matches some item of ``b``."""
    seen = {key(item) for item in b}
    return [item for item in a if key(item) in seen]
  1. order and duplicates come from a, never from b
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> from math import floorpassed on Python 3.11 to 3.14: >>> intersection_by([2.1, 1.2], [2.3, 3.4], floor)[2.1]passed on Python 3.11 to 3.14: >>> intersection_by(["Ada", "bob"], ["ADA", "Cy"], str.lower)['Ada']
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

  • Same shape as difference_by, with in instead of not in.
  • The result always holds items from a, never from b.

Complexity: O(n + m) time, O(m) space

Importfrom pysnippets.lists.intersection_by import intersection_byNo dependencies: copy intersection_by.py into your project, or clone the repo.

Adapted from intersection-by in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Typed; added a case-insensitive example. Suggest an edit.