This rule raises an issue when a for-loop adds every element of a collection to a list through append().
Adding elements to a list one at a time is unnecessary when the extend() method exists. This happens when a for-loop appends every
element of another collection:
for element in other_collection:
my_list.append(element)
The extend() method adds all elements in a single call and avoids the overhead of repeated append() invocations:
my_list.extend(other_collection)
Replacing the loop makes the intent explicit: the reader sees one operation that grows the list instead of an iteration whose body has to be read. It also removes redundant call overhead, since the attribute lookup and the method call are resolved once instead of once per element. In hot code or when the source collection is large, the difference becomes measurable.
No issue is raised when the body of the loop does more than append the loop variable, for example when it filters or transforms the elements:
for element in other_collection:
if element.is_valid():
my_list.append(element)
Replace the loop with a single extend() call and pass the iterated collection directly, as extend() accepts any
iterable.
def collect_results(results, new_results):
for result in new_results:
results.append(result) # Noncompliant
return results
def collect_results(results, new_results):
results.extend(new_results)
return results
extend() iterates over its argument and appends every element to the list, so the result is exactly the same as the loop. The
augmented assignment my_list += other_collection is equivalent to extend() and can be used instead when it reads better.
Do not confuse extend() with append(): my_list.append(other_collection) adds the collection itself as a
single element, while extend() adds its elements.
A loop that appends to the list it iterates over never terminates, while my_list.extend(my_list) simply doubles the list. Make sure
the loop you replace iterates over a different collection.
After a for-loop, the loop variable stays bound to the last element, while extend() defines no variable. If code after the loop reads
that variable, keep it defined before replacing the loop.
list.extend() methodlist, tuple, range