Improve List Extension

ID

python.improve_list_extension

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Python

Tags

best-practice, efficiency

Description

Reports for loops whose only statement is dest.append(item) where item is the loop variable. The loop is the verbose form of dest.extend(source); the idiomatic form is shorter, runs in C, and reads more clearly.

for item in source:
    dest.append(item)              # FLAW

dest.extend(source)                # OK
dest += list(source)               # OK

Rationale

extend is implemented in C and resizes the destination once based on the source’s length (when known). The Python-level for plus append does the same logical work with one bytecode interpretation per element — measurable on large iterables and a clearer signal of intent on small ones.

Remediation

dest.extend(source)
# or, when accumulating from multiple sources:
dest.extend(a)
dest.extend(b)
# or use a comprehension to filter / transform:
dest.extend(item for item in source if predicate(item))