Skip to content

list-front-pop (OPT120)

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

Opt-in: size-dependent q.pop(0) / del q[0] / q = q[1:] -> collections.deque.

What it does

Checks loops that remove the first element of a list: q.pop(0), del q[0], and q = q[1:], and suggests a collections.deque with popleft().

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.

The rewrite changes the list's creation to collections.deque(...), rewrites the variable's list[...] annotation to collections.deque[...], and adds import collections when needed: in sorted position among the module's standard-library imports, or after the docstring and __future__ imports of a module without other imports.

Not reported: a small display that the loop only drains (expected = [b"a", b""] and expected.pop(0) in the loop: it never holds more than its items), and a list rebuilt in every iteration of the loop.

What a report states

A report states that removing the first element of the list (lst.pop(0), del lst[0], lst = lst[1:]), in a loop, moves or copies every remaining 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?

Removing the first element shifts every remaining element, so a queue drained this way is quadratic. deque.popleft() is constant time.

Example

def bfs(graph: dict[int, list[int]], start: int) -> list[int]:
    queue = [start]
    seen = {start}
    order = []
    while queue:
        node = queue.pop(0)
        order.append(node)
        for child in graph[node]:
            if child not in seen:
                seen.add(child)
                queue.append(child)
    return order

Use instead:

import collections


def bfs(graph: dict[int, list[int]], start: int) -> list[int]:
    queue = collections.deque([start])
    seen = {start}
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for child in graph[node]:
            if child not in seen:
                seen.add(child)
                queue.append(child)
    return order

Fix safety

Proven safe only when the list is created in the function, never leaves it (not returned, stored, or passed to other code except read-only builtins such as len), and every use has a deque equivalent: no sorting, no slicing, no indexes other than 0 and -1, no == against lists, and no text of it (a replacement field of an f-string, str()), which differs for a deque. An annotation the rewrite cannot turn into a deque one (Sequence[str], a union) or another annotated declaration of the variable blocks the fix, so that a type checker accepts the fixed file. So does any other binding of a variable the list reaches, since a type checker gives the variable one type: s = [...] before s = q, a later q = [...] the loop never sees, a for s in ..., or a parameter s.

A deque iterator raises RuntimeError when the deque changes under it and is another type than a list iterator: no iterator of the list may be live at a change, consumed by the changing call (q.extend(reversed(q))), or used for more than its elements (type(iter(q))). list(xs) of a value that is not a builtin container becomes deque(list(xs)), which keeps the length query list makes; list(**kw) and list(*args) block the fix (deque reads a second argument as maxlen), and so does a list a starred target or pattern makes (first, *q = items), which has no display to rewrite. Only q = q[1:] is a front pop: q[1:n] and q[1::2] are not.