This rule raises an issue when a for-loop adds every element of a collection to a set through add().

Why is this an issue?

Adding elements to a set one at a time is unnecessary when the update() method exists. This happens when a for-loop adds every element of another collection:

for element in other_collection:
    my_set.add(element)

The update() method adds all elements in a single call and avoids the overhead of repeated add() invocations:

my_set.update(other_collection)

What is the potential impact?

Replacing the loop makes the intent explicit: the reader sees one operation that grows the set 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.

Exceptions

No issue is raised when the body of the loop does more than add the loop variable, for example when it filters or transforms the elements:

for element in other_collection:
    if element.is_valid():
        my_set.add(element)

How to fix it

Replace the loop with a single update() call and pass the iterated collection directly, as update() accepts any iterable.

Code examples

Noncompliant code example

def collect_results(results, new_results):
    for result in new_results:
        results.add(result)  # Noncompliant
    return results

Compliant solution

def collect_results(results, new_results):
    results.update(new_results)
    return results

How does this work?

update() iterates over its argument and adds every element to the set, so the result is exactly the same as the loop. The augmented assignment my_set |= other_set is equivalent to update() with another set and can be used instead when it is more readable.

Pitfalls

Do not confuse update() with add(): my_set.add(other_collection) adds the collection itself as a single element, and fails when that collection is not hashable, while update() adds its elements.

A loop that adds to the set it iterates over only re-adds elements that are already present, so it leaves the set unchanged and there is nothing to group. After a for-loop, the loop variable stays bound to the last element, while update() defines no variable. If code after the loop reads that variable, keep it defined before replacing the loop.

Resources

Documentation

Related rules