This rule raises an issue when several elements are added to the same list through consecutive append() calls.
Adding elements to a list one statement at a time is unnecessary when the extend() method exists:
my_list.append(first) my_list.append(second) my_list.append(third)
The extend() method combines all additions into a single call and avoids the overhead of repeated append()
invocations:
my_list.extend([first, second, third])
Grouping the additions makes the intent explicit: the reader sees one operation that grows the list instead of a series of independent statements. It also removes redundant call overhead, since the attribute lookup and the method call are resolved once instead of once per element.
No issue is raised when fewer than three consecutive calls target the list, or when other statements are interleaved between the
append() calls:
my_list.append(first)
log.debug("first added")
my_list.append(second)
my_list.append(third)
No issue is raised either when an added element reads the list, such as my_list.append(len(my_list)), because grouping the calls would
change the result.
Group the appended elements into a single extend() call, passing them as a list literal.
def build_command(base_command, path):
command = list(base_command)
command.append("--archive") # Noncompliant
command.append("--verbose")
command.append(path)
return command
def build_command(base_command, path):
command = list(base_command)
command.extend(["--archive", "--verbose", path])
return command
extend() iterates over its argument and appends every element to the list, so the result is exactly the same as the individual calls.
The augmented assignment my_list += [first, second, third] is equivalent to extend() and can be used instead when it reads
better.
Do not confuse extend() with append(): my_list.append([first, second]) adds the list itself as a single
element, while extend() adds its elements.
list.extend() methodlist, tuple, range