← All lints

copy_comprehension

L0549Idiomswarn

List copied by a comprehension

[x for x in a]: a.collect() copies a sequence into a List

Flagged
let n: 1..=100 = read()
let a: [0..n]Int = read()
var b: List<Int> = [x for x in a]
b.push(0)
print(b)
Write instead
let n: 1..=100 = read()
let a: [0..n]Int = read()
var b: List<Int> = a.collect()
b.push(0)
print(b)

Why

A comprehension whose body is its own loop variable, [x for x in a], only copies a. a.collect() says that: it copies any sequence (a list, a table, a range, a string, a filtered view) into a new List. A comprehension that transforms or filters is not reported. There is no automatic fix yet, because a set or a map is not a sequence and needs its own spelling.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

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

Near miss
let n: 1..=100 = read()
let a: [0..n]Int = read()
var b: List<Int> = [x * 2 for x in a]
b.push(0)
print(b)

Turn it off

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

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