Skip to content

list-front-insert (OPT121)

Family: Complexity Rewrites (OPT) · Exact · Opt-in · Severity warning (slower code) · Proven-safe suggestion (--fix --include-size-dependent)

Opt-in: size-dependent q.insert(0, v) -> collections.deque.

What it does

Checks loops that insert at the front of a list, q.insert(0, v), and suggests a collections.deque with appendleft(v).

Opt-in and size-dependent: it runs when extend-select names it or with --include-size-dependent, which also applies its proven rewrites with --fix. A list rebuilt in every iteration of the loop is not reported: its front insert costs no more than building it.

What a report states

A report states that inserting at the front of the list (lst.insert(0, x)), in a loop, moves every element each time it runs.

Its premises:

  • Builtin type by construction: the value is a builtin list by its construction (a display, a comprehension, list(...)). Established: the Soundness lane takes types from constructions only, never from annotations.
  • In a loop: the statement is in the body of a loop. Established by the IR.
  • Rewrite proven safe: the help says [safe fix: ...], [proven-safe suggestion: ...], or [proven safe; ...]. A report whose help names a blocking obligation instead ([not auto-fixable: ...]) lacks this premise and is heuristic whatever the rule's certainty; the proven reports are the rule's exact tier.

Not part of the claim: how many times the statement runs (one under a branch inside the loop counts), and how large the loop or the list is. The message claims no size and no cost estimate. A loop or a list that the code fixes at 16 or fewer items is not reported, since the rewrite would not pay off. The exact tier also asks that the data decide how many times the loop runs: the loop steps through a parameter (*args included) or a part of one, the rows of a query, the lines of a file, or the entries of a directory, as EFF103's Origin establishes them, and the code does not fix or cap their number. A proven report over any other loop is heuristic, for example over a loop whose trip count the code fixes at more than 16 or caps with a length test every path to the loop passes, over the program's structure (an attribute of self, a project function's result, range of a configured number, a class's MRO, a module-level list), or in a while loop. Such a report is true, but its loop usually runs a few times, however large the input.

Why is this bad?

Inserting at the front shifts every element, so building a list this way is quadratic.

Example

def reverse(items: list[int]) -> list[int]:
    out = []
    for i in items:
        out.insert(0, i)
    return list(out)

Use instead:

import collections


def reverse(items: list[int]) -> list[int]:
    out = collections.deque()
    for i in items:
        out.appendleft(i)
    return list(out)

Fix safety

The same obligations as OPT120, and the same rewrite of annotations and imports.