← All lints

push_loop

L0507Idiomswarn

Loop that only pushes

a list built by a loop that only pushes: a comprehension

Flagged
let raw = [3, 1, 2]
var doubled: List<Int> = []
for x in raw: doubled.push(2 * x)
print(doubled)
Write instead
let raw = [3, 1, 2]
let doubled = [2 * x for x in raw]
print(doubled)

Why

A var xs = [..] followed by a loop whose only statement is xs.push(e): a comprehension written as a loop. Write the list: [e for x in xs] (with if c for a filtered loop, head + [..] after a non-empty start). cpl lint --fix rewrites it.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.seq: building.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let raw = [3, 1, 2]
var seen: List<Int> = []
for x in raw:
    if not seen.contains(x): seen.push(x)
    print(seen.len)

Turn it off

For one block, wrap it in with lint(push_loop: allow):. For a project, add push_loop = "allow" under [lints] in cp.toml.

Generated from spec/lints/push_loop, the same record the linter is built from.