Skip to content

loop-linear-list-lookup (OPT112)

Family: Complexity Rewrites (OPT) · Heuristic · Off by default · Severity warning (slower code) · No automatic fix

Size-dependent list.index / list.remove / list.count inside a loop (repeated linear scans).

Heuristic

This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs when select or extend-select names its code or name, and with lint.heuristic = true (--heuristic) also by default and for its prefixes and ALL. Of 50 sampled reports (round 3, 2026-11-21), 90% were right about the code. See Rule Precision.

What it does

Checks list.index(), list.remove(), and list.count() calls that run on every iteration of a loop, on a list that outlives the iteration.

The receiver must certainly be a builtin list: a list display or comprehension, list(...), or a list[...] / List[...] annotation on a parameter, a local, or a class attribute (self.items). Calls on a set, a str, a project class, or a receiver of unknown type are not reported. Neither are:

  • loops whose size does not depend on the data: small constant ranges and displays (for i in range(3), for s in SUFFIXES with SUFFIXES = (".py", ".pyi"), also through enumerate / zip / reversed / sorted / .items() and range(ATTEMPTS - 1) with a constant ATTEMPTS), retry loops, and daemon polling loops; the iterable of a for loop, which runs once;
  • lists built in the iteration (parts = [...] inside the loop) and lists of the loop element (row.cells.index(x));
  • small lists: a display of at most 16 items that nothing grows (the loop may shrink it with remove() / pop() or replace its items), in the function, as a module global (also of another module: LEVELS = ["low", "mid", "high"]), or as an attribute its class and subclasses only ever assign such a display (self.preferred = [",", ";"], a class attribute); also a list the code builds from a fixed iterable (list(range(7)), [c for c in LABELS if overflow.get(c)]) or fills a fixed number of times (ids.append(card["id"]) for each of at most 6 cards a test allowed). A display handed to code that may grow it (any call but read-only builtins; a *items argument passes the items only) is not small;
  • calls after which the loop always ends (return items.index(x), a break on every path);
  • index(x, start), which scans from a position that usually moves forward.

What a report states

A report states that xs.index(...), xs.remove(...), or xs.count(...), in a loop, scans the list each time it runs (count scans all of it; index and remove scan up to the first match).

Its premises:

  • List: the receiver is a list, by construction or annotation (assumption R2).
  • In a loop: the call is in the body of a loop that can run it again on the same list. Established. How many times it runs is not part of the claim: a call under a branch counts.
  • Data-sized: the code does not fix the sizes the cost depends on (the loop's and the container's) at 16 or fewer. Open: a size heki cannot bound counts as data-sized.

Why is this bad?

Each call scans the list from the start (and remove() also shifts the elements after the removed one), so the loop costs the product of the loop size and the list size: O(n²) when both grow with the input. A dict or set built once before the loop answers each lookup in constant time, and collections.Counter counts every value in one pass.

Example

def ranks(names: list[str], winners: list[str]) -> list[int]:
    return [names.index(w) for w in winners]


def drop(items: list[int], unwanted: list[int]) -> None:
    for x in unwanted:
        items.remove(x)

Use instead:

def ranks(names: list[str], winners: list[str]) -> list[int]:
    position = {}
    for i, name in enumerate(names):
        position.setdefault(name, i)  # the first index, as `list.index`
    return [position[w] for w in winners]  # `KeyError` where `index` raised `ValueError`


def drop(items: list[int], unwanted: list[int]) -> None:
    gone = set(unwanted)
    items[:] = [x for x in items if x not in gone]

The rewrites are not drop-in replacements: remove() drops only the first occurrence of each value and raises ValueError for a missing one, and the values must be hashable.

The advice follows what the loop does with the list. Removals can wait for one rebuild after the loop only when the loop reads the list nowhere else (a membership test guarding the removal, if x in items: items.remove(x), aside); when it iterates, tests, indexes, or passes on the list after a removal (a greedy match over the remaining values), the help advises a set or a dict with constant-time deletion instead. An index or a count built once before the loop stays right only while the loop does not change the list, in place or through a project function it hands the list to (change(names) where change calls names.reverse()); otherwise the help advises keeping it up to date with each change.

Fix safety

No automatic fix.